@kontextmind/kxm
Version:
KXM local-first multi-agent orchestration and operator dashboard
36,839 lines • 1.48 MB
JavaScript
import { createRequire as __kxmCreateRequire } from 'node:module'; const require = __kxmCreateRequire(import.meta.url);
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
try {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
} catch (e) {
throw mod = 0, e;
}
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// node_modules/ajv/dist/compile/codegen/code.js
var require_code = __commonJS({
"node_modules/ajv/dist/compile/codegen/code.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
var _CodeOrName = class {
};
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var Name = class extends _CodeOrName {
constructor(s) {
super();
if (!exports.IDENTIFIER.test(s))
throw new Error("CodeGen: name must be a valid identifier");
this.str = s;
}
toString() {
return this.str;
}
emptyStr() {
return false;
}
get names() {
return { [this.str]: 1 };
}
};
exports.Name = Name;
var _Code = class extends _CodeOrName {
constructor(code) {
super();
this._items = typeof code === "string" ? [code] : code;
}
toString() {
return this.str;
}
emptyStr() {
if (this._items.length > 1)
return false;
const item = this._items[0];
return item === "" || item === '""';
}
get str() {
var _a;
return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
}
get names() {
var _a;
return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names3, c) => {
if (c instanceof Name)
names3[c.str] = (names3[c.str] || 0) + 1;
return names3;
}, {});
}
};
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
const code = [strs[0]];
let i = 0;
while (i < args.length) {
addCodeArg(code, args[i]);
code.push(strs[++i]);
}
return new _Code(code);
}
exports._ = _;
var plus = new _Code("+");
function str(strs, ...args) {
const expr = [safeStringify(strs[0])];
let i = 0;
while (i < args.length) {
expr.push(plus);
addCodeArg(expr, args[i]);
expr.push(plus, safeStringify(strs[++i]));
}
optimize(expr);
return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
if (arg instanceof _Code)
code.push(...arg._items);
else if (arg instanceof Name)
code.push(arg);
else
code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
let i = 1;
while (i < expr.length - 1) {
if (expr[i] === plus) {
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
if (res !== void 0) {
expr.splice(i - 1, 3, res);
continue;
}
expr[i++] = "+";
}
i++;
}
}
function mergeExprItems(a, b) {
if (b === '""')
return a;
if (a === '""')
return b;
if (typeof a == "string") {
if (b instanceof Name || a[a.length - 1] !== '"')
return;
if (typeof b != "string")
return `${a.slice(0, -1)}${b}"`;
if (b[0] === '"')
return a.slice(0, -1) + b.slice(1);
return;
}
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
return `"${a}${b.slice(1)}`;
return;
}
function strConcat(c1, c2) {
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
}
exports.strConcat = strConcat;
function interpolate(x) {
return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify7(x) {
return new _Code(safeStringify(x));
}
exports.stringify = stringify7;
function safeStringify(x) {
return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
}
exports.getProperty = getProperty;
function getEsmExportName(key) {
if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
return new _Code(`${key}`);
}
throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
}
});
// node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
"node_modules/ajv/dist/compile/codegen/scope.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
var code_1 = require_code();
var ValueError = class extends Error {
constructor(name) {
super(`CodeGen: "code" for ${name} not defined`);
this.value = name.value;
}
};
var UsedValueState;
(function(UsedValueState2) {
UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
const: new code_1.Name("const"),
let: new code_1.Name("let"),
var: new code_1.Name("var")
};
var Scope = class {
constructor({ prefixes, parent } = {}) {
this._names = {};
this._prefixes = prefixes;
this._parent = parent;
}
toName(nameOrPrefix) {
return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
}
name(prefix) {
return new code_1.Name(this._newName(prefix));
}
_newName(prefix) {
const ng = this._names[prefix] || this._nameGroup(prefix);
return `${prefix}${ng.index++}`;
}
_nameGroup(prefix) {
var _a, _b;
if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
}
return this._names[prefix] = { prefix, index: 0 };
}
};
exports.Scope = Scope;
var ValueScopeName = class extends code_1.Name {
constructor(prefix, nameStr) {
super(nameStr);
this.prefix = prefix;
}
setValue(value, { property, itemIndex }) {
this.value = value;
this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
}
};
exports.ValueScopeName = ValueScopeName;
var line = (0, code_1._)`\n`;
var ValueScope = class extends Scope {
constructor(opts) {
super(opts);
this._values = {};
this._scope = opts.scope;
this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
}
get() {
return this._scope;
}
name(prefix) {
return new ValueScopeName(prefix, this._newName(prefix));
}
value(nameOrPrefix, value) {
var _a;
if (value.ref === void 0)
throw new Error("CodeGen: ref must be passed in value");
const name = this.toName(nameOrPrefix);
const { prefix } = name;
const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
let vs = this._values[prefix];
if (vs) {
const _name = vs.get(valueKey);
if (_name)
return _name;
} else {
vs = this._values[prefix] = /* @__PURE__ */ new Map();
}
vs.set(valueKey, name);
const s = this._scope[prefix] || (this._scope[prefix] = []);
const itemIndex = s.length;
s[itemIndex] = value.ref;
name.setValue(value, { property: prefix, itemIndex });
return name;
}
getValue(prefix, keyOrRef) {
const vs = this._values[prefix];
if (!vs)
return;
return vs.get(keyOrRef);
}
scopeRefs(scopeName, values = this._values) {
return this._reduceValues(values, (name) => {
if (name.scopePath === void 0)
throw new Error(`CodeGen: name "${name}" has no value`);
return (0, code_1._)`${scopeName}${name.scopePath}`;
});
}
scopeCode(values = this._values, usedValues, getCode) {
return this._reduceValues(values, (name) => {
if (name.value === void 0)
throw new Error(`CodeGen: name "${name}" has no value`);
return name.value.code;
}, usedValues, getCode);
}
_reduceValues(values, valueCode, usedValues = {}, getCode) {
let code = code_1.nil;
for (const prefix in values) {
const vs = values[prefix];
if (!vs)
continue;
const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
vs.forEach((name) => {
if (nameSet.has(name))
return;
nameSet.set(name, UsedValueState.Started);
let c = valueCode(name);
if (c) {
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;
} else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) {
code = (0, code_1._)`${code}${c}${this.opts._n}`;
} else {
throw new ValueError(name);
}
nameSet.set(name, UsedValueState.Completed);
});
}
return code;
}
};
exports.ValueScope = ValueScope;
}
});
// node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
"node_modules/ajv/dist/compile/codegen/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
var code_1 = require_code();
var scope_1 = require_scope();
var code_2 = require_code();
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
return code_2._;
} });
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
return code_2.str;
} });
Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {
return code_2.strConcat;
} });
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
return code_2.nil;
} });
Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {
return code_2.getProperty;
} });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
return code_2.stringify;
} });
Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {
return code_2.regexpCode;
} });
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
return code_2.Name;
} });
var scope_2 = require_scope();
Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {
return scope_2.Scope;
} });
Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {
return scope_2.ValueScope;
} });
Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {
return scope_2.ValueScopeName;
} });
Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {
return scope_2.varKinds;
} });
exports.operators = {
GT: new code_1._Code(">"),
GTE: new code_1._Code(">="),
LT: new code_1._Code("<"),
LTE: new code_1._Code("<="),
EQ: new code_1._Code("==="),
NEQ: new code_1._Code("!=="),
NOT: new code_1._Code("!"),
OR: new code_1._Code("||"),
AND: new code_1._Code("&&"),
ADD: new code_1._Code("+")
};
var Node = class {
optimizeNodes() {
return this;
}
optimizeNames(_names, _constants) {
return this;
}
};
var Def = class extends Node {
constructor(varKind, name, rhs) {
super();
this.varKind = varKind;
this.name = name;
this.rhs = rhs;
}
render({ es5, _n }) {
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
return `${varKind} ${this.name}${rhs};` + _n;
}
optimizeNames(names3, constants) {
if (!names3[this.name.str])
return;
if (this.rhs)
this.rhs = optimizeExpr(this.rhs, names3, constants);
return this;
}
get names() {
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
}
};
var Assign = class extends Node {
constructor(lhs, rhs, sideEffects) {
super();
this.lhs = lhs;
this.rhs = rhs;
this.sideEffects = sideEffects;
}
render({ _n }) {
return `${this.lhs} = ${this.rhs};` + _n;
}
optimizeNames(names3, constants) {
if (this.lhs instanceof code_1.Name && !names3[this.lhs.str] && !this.sideEffects)
return;
this.rhs = optimizeExpr(this.rhs, names3, constants);
return this;
}
get names() {
const names3 = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
return addExprNames(names3, this.rhs);
}
};
var AssignOp = class extends Assign {
constructor(lhs, op, rhs, sideEffects) {
super(lhs, rhs, sideEffects);
this.op = op;
}
render({ _n }) {
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
}
};
var Label = class extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
return `${this.label}:` + _n;
}
};
var Break = class extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
const label = this.label ? ` ${this.label}` : "";
return `break${label};` + _n;
}
};
var Throw = class extends Node {
constructor(error) {
super();
this.error = error;
}
render({ _n }) {
return `throw ${this.error};` + _n;
}
get names() {
return this.error.names;
}
};
var AnyCode = class extends Node {
constructor(code) {
super();
this.code = code;
}
render({ _n }) {
return `${this.code};` + _n;
}
optimizeNodes() {
return `${this.code}` ? this : void 0;
}
optimizeNames(names3, constants) {
this.code = optimizeExpr(this.code, names3, constants);
return this;
}
get names() {
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
}
};
var ParentNode = class extends Node {
constructor(nodes = []) {
super();
this.nodes = nodes;
}
render(opts) {
return this.nodes.reduce((code, n) => code + n.render(opts), "");
}
optimizeNodes() {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i].optimizeNodes();
if (Array.isArray(n))
nodes.splice(i, 1, ...n);
else if (n)
nodes[i] = n;
else
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : void 0;
}
optimizeNames(names3, constants) {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i];
if (n.optimizeNames(names3, constants))
continue;
subtractNames(names3, n.names);
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : void 0;
}
get names() {
return this.nodes.reduce((names3, n) => addNames(names3, n.names), {});
}
};
var BlockNode = class extends ParentNode {
render(opts) {
return "{" + opts._n + super.render(opts) + "}" + opts._n;
}
};
var Root = class extends ParentNode {
};
var Else = class extends BlockNode {
};
Else.kind = "else";
var If = class _If extends BlockNode {
constructor(condition, nodes) {
super(nodes);
this.condition = condition;
}
render(opts) {
let code = `if(${this.condition})` + super.render(opts);
if (this.else)
code += "else " + this.else.render(opts);
return code;
}
optimizeNodes() {
super.optimizeNodes();
const cond = this.condition;
if (cond === true)
return this.nodes;
let e = this.else;
if (e) {
const ns = e.optimizeNodes();
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
}
if (e) {
if (cond === false)
return e instanceof _If ? e : e.nodes;
if (this.nodes.length)
return this;
return new _If(not(cond), e instanceof _If ? [e] : e.nodes);
}
if (cond === false || !this.nodes.length)
return void 0;
return this;
}
optimizeNames(names3, constants) {
var _a;
this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names3, constants);
if (!(super.optimizeNames(names3, constants) || this.else))
return;
this.condition = optimizeExpr(this.condition, names3, constants);
return this;
}
get names() {
const names3 = super.names;
addExprNames(names3, this.condition);
if (this.else)
addNames(names3, this.else.names);
return names3;
}
};
If.kind = "if";
var For = class extends BlockNode {
};
For.kind = "for";
var ForLoop = class extends For {
constructor(iteration) {
super();
this.iteration = iteration;
}
render(opts) {
return `for(${this.iteration})` + super.render(opts);
}
optimizeNames(names3, constants) {
if (!super.optimizeNames(names3, constants))
return;
this.iteration = optimizeExpr(this.iteration, names3, constants);
return this;
}
get names() {
return addNames(super.names, this.iteration.names);
}
};
var ForRange = class extends For {
constructor(varKind, name, from, to) {
super();
this.varKind = varKind;
this.name = name;
this.from = from;
this.to = to;
}
render(opts) {
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
const { name, from, to } = this;
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
}
get names() {
const names3 = addExprNames(super.names, this.from);
return addExprNames(names3, this.to);
}
};
var ForIter = class extends For {
constructor(loop, varKind, name, iterable) {
super();
this.loop = loop;
this.varKind = varKind;
this.name = name;
this.iterable = iterable;
}
render(opts) {
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
}
optimizeNames(names3, constants) {
if (!super.optimizeNames(names3, constants))
return;
this.iterable = optimizeExpr(this.iterable, names3, constants);
return this;
}
get names() {
return addNames(super.names, this.iterable.names);
}
};
var Func = class extends BlockNode {
constructor(name, args, async) {
super();
this.name = name;
this.args = args;
this.async = async;
}
render(opts) {
const _async = this.async ? "async " : "";
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
}
};
Func.kind = "func";
var Return = class extends ParentNode {
render(opts) {
return "return " + super.render(opts);
}
};
Return.kind = "return";
var Try = class extends BlockNode {
render(opts) {
let code = "try" + super.render(opts);
if (this.catch)
code += this.catch.render(opts);
if (this.finally)
code += this.finally.render(opts);
return code;
}
optimizeNodes() {
var _a, _b;
super.optimizeNodes();
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
return this;
}
optimizeNames(names3, constants) {
var _a, _b;
super.optimizeNames(names3, constants);
(_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names3, constants);
(_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names3, constants);
return this;
}
get names() {
const names3 = super.names;
if (this.catch)
addNames(names3, this.catch.names);
if (this.finally)
addNames(names3, this.finally.names);
return names3;
}
};
var Catch = class extends BlockNode {
constructor(error) {
super();
this.error = error;
}
render(opts) {
return `catch(${this.error})` + super.render(opts);
}
};
Catch.kind = "catch";
var Finally = class extends BlockNode {
render(opts) {
return "finally" + super.render(opts);
}
};
Finally.kind = "finally";
var CodeGen = class {
constructor(extScope, opts = {}) {
this._values = {};
this._blockStarts = [];
this._constants = {};
this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
this._extScope = extScope;
this._scope = new scope_1.Scope({ parent: extScope });
this._nodes = [new Root()];
}
toString() {
return this._root.render(this.opts);
}
// returns unique name in the internal scope
name(prefix) {
return this._scope.name(prefix);
}
// reserves unique name in the external scope
scopeName(prefix) {
return this._extScope.name(prefix);
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName, value) {
const name = this._extScope.value(prefixOrName, value);
const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());
vs.add(name);
return name;
}
getScopeValue(prefix, keyOrRef) {
return this._extScope.getValue(prefix, keyOrRef);
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName) {
return this._extScope.scopeRefs(scopeName, this._values);
}
scopeCode() {
return this._extScope.scopeCode(this._values);
}
_def(varKind, nameOrPrefix, rhs, constant) {
const name = this._scope.toName(nameOrPrefix);
if (rhs !== void 0 && constant)
this._constants[name.str] = rhs;
this._leafNode(new Def(varKind, name, rhs));
return name;
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
}
// `var` declaration with optional assignment
var(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
}
// assignment code
assign(lhs, rhs, sideEffects) {
return this._leafNode(new Assign(lhs, rhs, sideEffects));
}
// `+=` code
add(lhs, rhs) {
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
}
// appends passed SafeExpr to code or executes Block
code(c) {
if (typeof c == "function")
c();
else if (c !== code_1.nil)
this._leafNode(new AnyCode(c));
return this;
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues) {
const code = ["{"];
for (const [key, value] of keyValues) {
if (code.length > 1)
code.push(",");
code.push(key);
if (key !== value || this.opts.es5) {
code.push(":");
(0, code_1.addCodeArg)(code, value);
}
}
code.push("}");
return new code_1._Code(code);
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition, thenBody, elseBody) {
this._blockNode(new If(condition));
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf();
} else if (thenBody) {
this.code(thenBody).endIf();
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body');
}
return this;
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition) {
return this._elseNode(new If(condition));
}
// `else` clause - only valid after `if` or `else if` clauses
else() {
return this._elseNode(new Else());
}
// end `if` statement (needed if gen.if was used only with condition)
endIf() {
return this._endBlockNode(If, Else);
}
_for(node, forBody) {
this._blockNode(node);
if (forBody)
this.code(forBody).endFor();
return this;
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration, forBody) {
return this._for(new ForLoop(iteration), forBody);
}
// `for` statement for a range of values
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
const name = this._scope.toName(nameOrPrefix);
if (this.opts.es5) {
const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => {
this.var(name, (0, code_1._)`${arr}[${i}]`);
forBody(name);
});
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
}
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
}
// end `for` loop
endFor() {
return this._endBlockNode(For);
}
// `label` statement
label(label) {
return this._leafNode(new Label(label));
}
// `break` statement
break(label) {
return this._leafNode(new Break(label));
}
// `return` statement
return(value) {
const node = new Return();
this._blockNode(node);
this.code(value);
if (node.nodes.length !== 1)
throw new Error('CodeGen: "return" should have one node');
return this._endBlockNode(Return);
}
// `try` statement
try(tryBody, catchCode, finallyCode) {
if (!catchCode && !finallyCode)
throw new Error('CodeGen: "try" without "catch" and "finally"');
const node = new Try();
this._blockNode(node);
this.code(tryBody);
if (catchCode) {
const error = this.name("e");
this._currNode = node.catch = new Catch(error);
catchCode(error);
}
if (finallyCode) {
this._currNode = node.finally = new Finally();
this.code(finallyCode);
}
return this._endBlockNode(Catch, Finally);
}
// `throw` statement
throw(error) {
return this._leafNode(new Throw(error));
}
// start self-balancing block
block(body, nodeCount) {
this._blockStarts.push(this._nodes.length);
if (body)
this.code(body).endBlock(nodeCount);
return this;
}
// end the current self-balancing block
endBlock(nodeCount) {
const len = this._blockStarts.pop();
if (len === void 0)
throw new Error("CodeGen: not in self-balancing block");
const toClose = this._nodes.length - len;
if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
}
this._nodes.length = len;
return this;
}
// `function` heading (or definition if funcBody is passed)
func(name, args = code_1.nil, async, funcBody) {
this._blockNode(new Func(name, args, async));
if (funcBody)
this.code(funcBody).endFunc();
return this;
}
// end function definition
endFunc() {
return this._endBlockNode(Func);
}
optimize(n = 1) {
while (n-- > 0) {
this._root.optimizeNodes();
this._root.optimizeNames(this._root.names, this._constants);
}
}
_leafNode(node) {
this._currNode.nodes.push(node);
return this;
}
_blockNode(node) {
this._currNode.nodes.push(node);
this._nodes.push(node);
}
_endBlockNode(N1, N2) {
const n = this._currNode;
if (n instanceof N1 || N2 && n instanceof N2) {
this._nodes.pop();
return this;
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
}
_elseNode(node) {
const n = this._currNode;
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"');
}
this._currNode = n.else = node;
return this;
}
get _root() {
return this._nodes[0];
}
get _currNode() {
const ns = this._nodes;
return ns[ns.length - 1];
}
set _currNode(node) {
const ns = this._nodes;
ns[ns.length - 1] = node;
}
};
exports.CodeGen = CodeGen;
function addNames(names3, from) {
for (const n in from)
names3[n] = (names3[n] || 0) + (from[n] || 0);
return names3;
}
function addExprNames(names3, from) {
return from instanceof code_1._CodeOrName ? addNames(names3, from.names) : names3;
}
function optimizeExpr(expr, names3, constants) {
if (expr instanceof code_1.Name)
return replaceName(expr);
if (!canOptimize(expr))
return expr;
return new code_1._Code(expr._items.reduce((items, c) => {
if (c instanceof code_1.Name)
c = replaceName(c);
if (c instanceof code_1._Code)
items.push(...c._items);
else
items.push(c);
return items;
}, []));
function replaceName(n) {
const c = constants[n.str];
if (c === void 0 || names3[n.str] !== 1)
return n;
delete names3[n.str];
return c;
}
function canOptimize(e) {
return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names3[c.str] === 1 && constants[c.str] !== void 0);
}
}
function subtractNames(names3, from) {
for (const n in from)
names3[n] = (names3[n] || 0) - (from[n] || 0);
}
function not(x) {
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
}
exports.not = not;
var andCode = mappend(exports.operators.AND);
function and(...args) {
return args.reduce(andCode);
}
exports.and = and;
var orCode = mappend(exports.operators.OR);
function or(...args) {
return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
}
function par(x) {
return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
}
}
});
// node_modules/ajv/dist/compile/util.js
var require_util = __commonJS({
"node_modules/ajv/dist/compile/util.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
var codegen_1 = require_codegen();
var code_1 = require_code();
function toHash(arr) {
const hash = {};
for (const item of arr)
hash[item] = true;
return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
if (typeof schema == "boolean")
return schema;
if (Object.keys(schema).length === 0)
return true;
checkUnknownRules(it, schema);
return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
const { opts, self } = it;
if (!opts.strictSchema)
return;
if (typeof schema === "boolean")
return;
const rules = self.RULES.keywords;
for (const key in schema) {
if (!rules[key])
checkStrictMode(it, `unknown keyword: "${key}"`);
}
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (rules[key])
return true;
return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (key !== "$ref" && RULES.all[key])
return true;
return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
if (!$data) {
if (typeof schema == "number" || typeof schema == "boolean")
return schema;
if (typeof schema == "string")
return (0, codegen_1._)`${schema}`;
}
return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
if (typeof str == "number")
return `${str}`;
return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
if (Array.isArray(xs)) {
for (const x of xs)
f(x);
} else {
f(xs);
}
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) {
return (gen, from, to, toName) => {
const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to);
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
};
}
exports.mergeEvaluated = {
props: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
}),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
if (from === true) {
gen.assign(to, true);
} else {
gen.assign(to, (0, codegen_1._)`${to} || {}`);
setEvaluated(gen, to, from);
}
}),
mergeValues: (from, to) => from === true ? true : { ...from, ...to },
resultToName: evaluatedPropsToName
}),
items: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
mergeValues: (from, to) => from === true ? true : Math.max(from, to),
resultToName: (gen, items) => gen.var("items", items)
})
};
function evaluatedPropsToName(gen, ps) {
if (ps === true)
return gen.var("props", true);
const props = gen.var("props", (0, codegen_1._)`{}`);
if (ps !== void 0)
setEvaluated(gen, props, ps);
return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
var snippets = {};
function useFunc(gen, f) {
return gen.scopeValue("func", {
ref: f,
code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
});
}
exports.useFunc = useFunc;
var Type;
(function(Type2) {
Type2[Type2["Num"] = 0] = "Num";
Type2[Type2["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
if (dataProp instanceof codegen_1.Name) {
const isNumber = dataPropType === Type.Num;
return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
}
return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
if (!mode)
return;
msg = `strict mode: ${msg}`;
if (mode === true)
throw new Error(msg);
it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
}
});
// node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
"node_modules/ajv/dist/compile/names.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var names3 = {
// validation function arguments
data: new codegen_1.Name("data"),
// data passed to validation function
// args passed from referencing schema
valCxt: new codegen_1.Name("valCxt"),
// validation/data context - should not be used directly, it is destructured to the names below
instancePath: new codegen_1.Name("instancePath"),
parentData: new codegen_1.Name("parentData"),
parentDataProperty: new codegen_1.Name("parentDataProperty"),
rootData: new codegen_1.Name("rootData"),
// root data - same as the data passed to the first/top validation function
dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
// used to support recursiveRef and dynamicRef
// function scoped variables
vErrors: new codegen_1.Name("vErrors"),
// null or array of validation errors
errors: new codegen_1.Name("errors"),
// counter of validation errors
this: new codegen_1.Name("this"),
// "globals"
self: new codegen_1.Name("self"),
scope: new codegen_1.Name("scope"),
// JTD serialize/parse name for JSON string and position
json: new codegen_1.Name("json"),
jsonPos: new codegen_1.Name("jsonPos"),
jsonLen: new codegen_1.Name("jsonLen"),
jsonPart: new codegen_1.Name("jsonPart")
};
exports.default = names3;
}
});
// node_modules/ajv/dist/compile/errors.js
var require_errors = __commonJS({
"node_modules/ajv/dist/compile/errors.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
var names_1 = require_names();
exports.keywordError = {
message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`
};
exports.keyword$DataError = {
message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
addError(gen, errObj);
} else {
returnErrors(it, (0, codegen_1._)`[${errObj}]`);
}
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
addError(gen, errObj);
if (!(compositeRule || allErrors)) {
returnErrors(it, names_1.default.vErrors);
}
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
gen.assign(names_1.default.errors, errsCount);
gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
if (errsCount === void 0)
throw new Error("ajv implementation error");
const err = gen.name("err");
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
if (it.opts.verbose) {
gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
gen.assign((0, codegen_1._)`${err}.data`, data);
}
});
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
const err = gen.const("err", errObj);
gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
gen.code((0, codegen_1._)`${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
const { gen, validateName, schemaEnv } = it;
if (schemaEnv.$async) {
gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
} else {
gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
gen.return(false);
}
}
var E = {
keyword: new codegen_1.Name("keyword"),
schemaPath: new codegen_1.Name("schemaPath"),
// also used in JTD errors
params: new codegen_1.Name("params"),
propertyName: new codegen_1.Name("propertyName"),
message: new codegen_1.Name("message"),
schema: new codegen_1.Name("schema"),
parentSchema: new codegen_1.Name("parentSchema")
};
function errorObjectCode(cxt, error, errorPaths) {
const { createErrors } = cxt.it;
if (createErrors === false)
return (0, codegen_1._)`{}`;
return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
const { gen, it } = cxt;
const keyValues = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths)
];
extraErrorProps(cxt, error, keyValues);
return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
if (schemaPath) {
schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
}
return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
const { keyword, data, schemaValue, it } = cxt;
const { opts, propertyName, topSchemaRef, schemaPath } = it;
keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
if (opts.messages) {
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
}
if (opts.verbose) {
keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
}
if (propertyName)
keyValues.push([E.propertyName, propertyName]);
}
}
});
// node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = __commonJS({
"node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
var errors_1 = require_errors();
var codegen_1 = require_codegen();
var names_1 = require_names();
var boolError = {
message: "boolean schema is false"
};
function topBoolOrEmptySchema(it) {
const { gen, schema, validateName } = it;
if (schema === false) {
falseSchemaError(it, false);
} else if (typeof schema == "object" && schema.$async === true) {
gen.return(names_1.default.data);
} else {
gen.assign((0, codegen_1._)`${validateName}.errors`, null);
gen.return(true);
}
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
const { gen, schema } = it;
if (schema === false) {
gen.var(valid, false);
falseSchemaError(it);
} else {
gen.var(valid, true);
}
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
const { gen, data } = it;
const cxt = {
gen,
keyword: "false schema",
data,
schema: false,
schemaCode: false,
schemaValue: false,
params: {},
it
};
(0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
}
}
});
// node_modules/ajv/dist/compile/rules.js
var require_rules = __commonJS({
"node_modules/ajv/dist/compile/rules.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRules = exports.isJSONType = void 0;
var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
var jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
const groups = {
number: { type: "number", rules: [] },
string: { type: "string", rules: [] },
array: { type: "array", rules: [] },
object: { type: "object", rules: [] }
};
return {
types: { ...groups, integer: true, boolean: true, null: true },
rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
post: { rules: [] },
all: {},
keywords: {}
};
}
exports.getRules = getRules;
}
});
// node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = __commonJS({
"node_modules/ajv/dist/compile/validate/applicability.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
const group = self.RULES.types[type];
return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
var _a;
return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0));
}
exports.shouldUseRule = shouldUseRule;
}
});
// node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType = __commonJS({
"node_modules/ajv/dist/compile/validate/dataType.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
var rules_1 = require_rules();
var applicability_1 = require_applicability();
var errors_1 = require_errors();
var codegen_1 = require_codegen();
var util_1 = require_util();
var DataType;
(function(DataType2) {
DataType2[DataType2["Correct"] = 0] = "Correct";
DataType2[DataType2["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
const types = getJSONTypes(schema.type);
const hasNull = types.includes("null");
if (hasNull) {
if (schema.nullable === false)
throw new Error("type: null contradicts nullable: false");
} else {
if (!types.length && schema.nullable !== void 0) {
throw new Error('"nullable" cannot be used without "type"');
}
if (schema.nullable === true)
types.push("null");
}
return types;
}
exports.getSchemaTypes = getSchemaTypes;
function getJSONTypes(ts) {
const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
if (types.every(rules_1.isJSONType))
return types;
throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
const { gen, data, opts } = it;
const coerceTo = coerceToTypes(types, opts.coerceTypes);
const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
if (checkTypes) {
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
gen.if(wrongType, () => {
if (coerceTo.length)
coerceData(it, types, coerceTo);
else
reportTypeError(it);
});
}
return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];
}
function coerceData(it, types, coerceTo) {
const { gen, data, opts } = it;
const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);
const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
if (opts.coerceTypes === "array") {
gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
}
gen.if((0, codegen_1._)`${coerced} !== undefined`);
for (const t of coerceTo) {
if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {
coerceSpecificType(t);
}
}
gen.else();
reportTypeError(it);
gen.endIf();
gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
gen.assign(data, coerced);
assignParentData(it, coerced);
});
function coerceSpecificType(t) {
switch (t) {
case "string":
gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
return;
case "number":
gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null
|| (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
return;
case "integer":
gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);
return;
case "boolean":
gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
return;
case "null":
gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);
gen.assign(coerced, null);
return;
case "array":
gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"
|| ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
}
}
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
let cond;
switch (dataType) {
case "null":
return (0, codegen_1._)`${data} ${EQ} null`;
case "array":
cond = (0, codegen_1._)`Array.isArray(${data})`;
break;
case "object":
cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
break;
case "integer":
cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
break;
case "number":
cond = numCond();
break;
default:
return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;
}
return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
function numCond(_cond = codegen_1.nil) {
return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
}
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
if (dataTypes.length === 1) {
return checkDataType(dataTypes[0], data, strictNums, correct);
}
let cond;
const types = (0, util_1.toHash)(dataTypes);
if (types.array && types.object) {
const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
delete types.null;
delete types.array;
delete types.object;
} else {
cond = codegen_1.nil;
}
if (types.number)
delete types.integer;
for (const t in types)
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
return cond;
}
exports.checkDataTypes = checkDataTypes;
var typeError = {
message: ({ schema }) => `must be ${schema}`,
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
};
function reportTypeError(it) {
const cxt = getTypeErrorContext(it);
(0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
const { gen, data, schema } = it;
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
return {
gen,
keyword: "type",
data,
schema: schema.type,
schemaCode,
schemaValue: schemaCode,
parentSchema: schema,
params: {},
it
};
}
}
});
// node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults = __commonJS({
"node_modules/ajv/dist/compile/validate/defaults.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignDefaults = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
function assignDefaults(it, ty) {
const { properties, items } = it.schema;
if (ty === "object" && properties) {
for (const key in properties) {
assignDefault(it, key, properties[key].default);
}
} else if (ty === "array" && Array.isArray(items)) {
items.forEach((sch, i) => assignDefault(it, i, sch.default));
}
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
const { gen, compositeRule, data, opts } = it;
if (defaultValue === void 0)
return;
const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
if (compositeRule) {
(0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
return;
}
let condition = (0, codegen_1._)`${childData} === undefined`;
if (opts.useDefaults === "empty") {
condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
}
gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
}
});
// node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
"node_modules/ajv/dist/vocabularies/code.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
var names_1 = require_names();
var util_2 = require_util();
function checkReportMissingProp(cxt, prop) {
const { gen, data, it } = cxt;
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
cxt.error();
});
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
cxt.setParams({ missingProperty: missing }, true);
cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
return gen.scopeValue("func", {
// eslint-disable-next-line @typescript-eslint/unbound-method
ref: Object.prototype.hasOwnProperty,
code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
});
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
const valCxt = [
[names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
[names_1.default.parentData, it.parentData],
[names_1.default.parentDataProperty, it.parentDataProperty],
[names_1.default.rootData, names_1.default.rootData]
];
if (it.opts.dynamicRef)
valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
var newRegExp = (0, codegen_1._)`new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
const u = opts.unicodeRegExp ? "u" : "";
const { regExp } = opts.code;
const rx = regExp(pattern, u);
return gen.scopeValue("pattern", {
key: rx.toString(),
ref: rx,
code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
});
}
exports.usePattern = usePattern;
function validateArray(cxt) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
if (it.allErrors) {
const validArr = gen.let("valid", true);
validateItems(() => gen.assign(validArr, false));
return validArr;
}
gen.var(valid, true);
validateItems(() => gen.break());
return valid;
function validateItems(notValid) {
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword,
dataProp: i,
dataPropType: util_1.Type.Num
}, valid);
gen.if((0, codegen_1.not)(valid), notValid);
});
}
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
const { gen, schema, keyword, it } = cxt;
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
if (alwaysValid && !it.opts.unevaluated)
return;
const valid = gen.let("valid", false);
const schValid = gen.name("_valid");
gen.block(() => schema.forEach((_sch, i) => {
const schCxt = cxt.subschema({
keyword,
schemaProp: i,
compositeRule: true
}, schValid);
gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
const merged = cxt.mergeValidEvaluated(schCxt, schValid);
if (!merged)
gen.if((0, codegen_1.not)(valid));
}));
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
}
});
// node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword = __commonJS({
"node_modules/ajv/dist/compile/validate/keyword.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
var codegen_1 = require_codegen();
var names_1 = require_names();
var code_1 = require_code2();
var errors_1 = require_errors();
function macroKeywordCode(cxt, def) {
const { gen, keyword, schema, parentSchema, it } = cxt;
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
const schemaRef = useKeyword(gen, keyword, macroSchema);
if (it.opts.validateSchema !== false)
it.self.validateSchema(macroSchema, true);
const valid = gen.name("valid");
cxt.subschema({
schema: macroSchema,
schemaPath: codegen_1.nil,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
topSchemaRef: schemaRef,
compositeRule: true
}, valid);
cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
var _a;
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
checkAsyncKeyword(it, def);
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
const validateRef = useKeyword(gen, keyword, validate);
const valid = gen.let("valid");
cxt.block$data(valid, validateKeyword);
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
function validateKeyword() {
if (def.errors === false) {
assignValid();
if (def.modifying)
modifyData(cxt);
reportErrs(() => cxt.error());
} else {
const ruleErrs = def.async ? validateAsync() : validateSync();
if (def.modifying)
modifyData(cxt);
reportErrs(() => addErrs(cxt, ruleErrs));
}
}
function validateAsync() {
const ruleErrs = gen.let("ruleErrs", null);
gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
return ruleErrs;
}
function validateSync() {
const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
gen.assign(validateErrs, null);
assignValid(codegen_1.nil);
return validateErrs;
}
function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
const passSchema = !("compile" in def && !$data || def.schema === false);
gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
}
function reportErrs(errors) {
var _a2;
gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors);
}
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
const { gen, data, it } = cxt;
gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
const { gen } = cxt;
gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
(0, errors_1.extendErrors)(cxt);
}, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
if (def.async && !schemaEnv.$async)
throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
if (result === void 0)
throw new Error(`keyword "${keyword}" failed to compile`);
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error");
}
const deps = def.dependencies;
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
}
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword]);
if (!valid) {
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors);
if (opts.validateSchema === "log")
self.logger.error(msg);
else
throw new Error(msg);
}
}
}
exports.validateKeywordUsage = validateKeywordUsage;
}
});
// node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema = __commonJS({
"node_modules/ajv/dist/compile/validate/subschema.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
if (keyword !== void 0 && schema !== void 0) {
throw new Error('both "keyword" and "schema" passed, only one allowed');
}
if (keyword !== void 0) {
const sch = it.schema[keyword];
return schemaProp === void 0 ? {
schema: sch,
schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}`
} : {
schema: sch[schemaProp],
schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`
};
}
if (schema !== void 0) {
if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
}
return {
schema,
schemaPath,
topSchemaRef,
errSchemaPath
};
}
throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
if (data !== void 0 && dataProp !== void 0) {
throw new Error('both "data" and "dataProp" passed, only one allowed');
}
const { gen } = it;
if (dataProp !== void 0) {
const { errorPath, dataPathArr, opts } = it;
const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
dataContextProps(nextData);
subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
}
if (data !== void 0) {
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
dataContextProps(nextData);
if (propertyName !== void 0)
subschema.propertyName = propertyName;
}
if (dataTypes)
subschema.dataTypes = dataTypes;
function dataContextProps(_nextData) {
subschema.data = _nextData;
subschema.dataLevel = it.dataLevel + 1;
subschema.dataTypes = [];
it.definedProperties = /* @__PURE__ */ new Set();
subschema.parentData = it.data;
subschema.dataNames = [...it.dataNames, _nextData];
}
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
if (compositeRule !== void 0)
subschema.compositeRule = compositeRule;
if (createErrors !== void 0)
subschema.createErrors = createErrors;
if (allErrors !== void 0)
subschema.allErrors = allErrors;
subschema.jtdDiscriminator = jtdDiscriminator;
subschema.jtdMetadata = jtdMetadata;
}
exports.extendSubschemaMode = extendSubschemaMode;
}
});
// node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
"node_modules/fast-deep-equal/index.js"(exports, module) {
"use strict";
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == "object" && typeof b == "object") {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0; )
if (!equal(a[i], b[i])) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0; )
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0; ) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
return a !== a && b !== b;
};
}
});
// node_modules/json-schema-traverse/index.js
var require_json_schema_traverse = __commonJS({
"node_modules/json-schema-traverse/index.js"(exports, module) {
"use strict";
var traverse = module.exports = function(schema, opts, cb) {
if (typeof opts == "function") {
cb = opts;
opts = {};
}
cb = opts.cb || cb;
var pre = typeof cb == "function" ? cb : cb.pre || function() {
};
var post = cb.post || function() {
};
_traverse(opts, pre, post, schema, "", schema);
};
traverse.keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
if: true,
then: true,
else: true
};
traverse.arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true
};
traverse.propsKeywords = {
$defs: true,
definitions: true,
properties: true,
patternProperties: true,
dependencies: true
};
traverse.skipKeywords = {
default: true,
enum: true,
const: true,
required: true,
maximum: true,
minimum: true,
exclusiveMaximum: true,
exclusiveMinimum: true,
multipleOf: true,
maxLength: true,
minLength: true,
pattern: true,
format: true,
maxItems: true,
minItems: true,
uniqueItems: true,
maxProperties: true,
minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (schema && typeof schema == "object" && !Array.isArray(schema)) {
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
for (var key in schema) {
var sch = schema[key];
if (Array.isArray(sch)) {
if (key in traverse.arrayKeywords) {
for (var i = 0; i < sch.length; i++)
_traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
}
} else if (key in traverse.propsKeywords) {
if (sch && typeof sch == "object") {
for (var prop in sch)
_traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
}
} else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
_traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
}
}
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
}
}
function escapeJsonPtr(str) {
return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
}
});
// node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
"node_modules/ajv/dist/compile/resolve.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
var util_1 = require_util();
var equal = require_fast_deep_equal();
var traverse = require_json_schema_traverse();
var SIMPLE_INLINED = /* @__PURE__ */ new Set([
"type",
"format",
"pattern",
"maxLength",
"minLength",
"maxProperties",
"minProperties",
"maxItems",
"minItems",
"maximum",
"minimum",
"uniqueItems",
"multipleOf",
"required",
"enum",
"const"
]);
function inlineRef(schema, limit = true) {
if (typeof schema == "boolean")
return true;
if (limit === true)
return !hasRef(schema);
if (!limit)
return false;
return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
var REF_KEYWORDS = /* @__PURE__ */ new Set([
"$ref",
"$recursiveRef",
"$recursiveAnchor",
"$dynamicRef",
"$dynamicAnchor"
]);
function hasRef(schema) {
for (const key in schema) {
if (REF_KEYWORDS.has(key))
return true;
const sch = schema[key];
if (Array.isArray(sch) && sch.some(hasRef))
return true;
if (typeof sch == "object" && hasRef(sch))
return true;
}
return false;
}
function countKeys(schema) {
let count = 0;
for (const key in schema) {
if (key === "$ref")
return Infinity;
count++;
if (SIMPLE_INLINED.has(key))
continue;
if (typeof schema[key] == "object") {
(0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
}
if (count === Infinity)
return Infinity;
}
return count;
}
function getFullPath(resolver, id = "", normalize) {
if (normalize !== false)
id = normalizeId(id);
const p = resolver.parse(id);
return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
const serialized = resolver.serialize(p);
return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
id = normalizeId(id);
return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
if (typeof schema == "boolean")
return {};
const { schemaId, uriResolver } = this.opts;
const schId = normalizeId(schema[schemaId] || baseId);
const baseIds = { "": schId };
const pathPrefix = getFullPath(uriResolver, schId, false);
const localRefs = {};
const schemaRefs = /* @__PURE__ */ new Set();
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === void 0)
return;
const fullPath = pathPrefix + jsonPtr;
let innerBaseId = baseIds[parentJsonPtr];
if (typeof sch[schemaId] == "string")
innerBaseId = addRef.call(this, sch[schemaId]);
addAnchor.call(this, sch.$anchor);
addAnchor.call(this, sch.$dynamicAnchor);
baseIds[jsonPtr] = innerBaseId;
function addRef(ref) {
const _resolve = this.opts.uriResolver.resolve;
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
if (schemaRefs.has(ref))
throw ambiguos(ref);
schemaRefs.add(ref);
let schOrRef = this.refs[ref];
if (typeof schOrRef == "string")
schOrRef = this.refs[schOrRef];
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref);
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref);
localRefs[ref] = sch;
} else {
this.refs[ref] = fullPath;
}
}
return ref;
}
function addAnchor(anchor) {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor))
throw new Error(`invalid anchor "${anchor}"`);
addRef.call(this, `#${anchor}`);
}
}
});
return localRefs;
function checkAmbiguosRef(sch1, sch2, ref) {
if (sch2 !== void 0 && !equal(sch1, sch2))
throw ambiguos(ref);
}
function ambiguos(ref) {
return new Error(`reference "${ref}" resolves to more than one schema`);
}
}
exports.getSchemaRefs = getSchemaRefs;
}
});
// node_modules/ajv/dist/compile/validate/index.js
var require_validate = __commonJS({
"node_modules/ajv/dist/compile/validate/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
var boolSchema_1 = require_boolSchema();
var dataType_1 = require_dataType();
var applicability_1 = require_applicability();
var dataType_2 = require_dataType();
var defaults_1 = require_defaults();
var keyword_1 = require_keyword();
var subschema_1 = require_subschema();
var codegen_1 = require_codegen();
var names_1 = require_names();
var resolve_1 = require_resolve();
var util_1 = require_util();
var errors_1 = require_errors();
function validateFunctionCode(it) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
topSchemaObjCode(it);
return;
}
}
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
if (opts.code.es5) {
gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
destructureValCxtES5(gen, opts);
gen.code(body);
});
} else {
gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
}
}
function destructureValCxt(opts) {
return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
gen.if(names_1.default.valCxt, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
}, () => {
gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
gen.var(names_1.default.rootData, names_1.default.data);
if (opts.dynamicRef)
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
});
}
function topSchemaObjCode(it) {
const { schema, opts, gen } = it;
validateFunction(it, () => {
if (opts.$comment && schema.$comment)
commentKeyword(it);
checkNoDefault(it);
gen.let(names_1.default.vErrors, null);
gen.let(names_1.default.errors, 0);
if (opts.unevaluated)
resetEvaluated(it);
typeAndKeywords(it);
returnResults(it);
});
return;
}
function resetEvaluated(it) {
const { gen, validateName } = it;
it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
}
function funcSourceUrl(schema, opts) {
const schId = typeof schema == "object" && schema[opts.schemaId];
return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
}
function subschemaCode(it, valid) {
if (isSchemaObj(it)) {
checkKeywords(it);
if (schemaCxtHasRules(it)) {
subSchemaObjCode(it, valid);
return;
}
}
(0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
if (typeof schema == "boolean")
return !schema;
for (const key in schema)
if (self.RULES.all[key])
return true;
return false;
}
function isSchemaObj(it) {
return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
const { schema, gen, opts } = it;
if (opts.$comment && schema.$comment)
commentKeyword(it);
updateContext(it);
checkAsyncSchema(it);
const errsCount = gen.const("_errs", names_1.default.errors);
typeAndKeywords(it, errsCount);
gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
(0, util_1.checkUnknownRules)(it);
checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
if (it.opts.jtd)
return schemaKeywords(it, [], false, errsCount);
const types = (0, dataType_1.getSchemaTypes)(it.schema);
const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
const { schema, errSchemaPath, opts, self } = it;
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
}
}
function checkNoDefault(it) {
const { schema, opts } = it;
if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
(0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
}
}
function updateContext(it) {
const schId = it.schema[it.opts.schemaId];
if (schId)
it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
if (it.schema.$async && !it.schemaEnv.$async)
throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
const msg = schema.$comment;
if (opts.$comment === true) {
gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
} else if (typeof opts.$comment == "function") {
const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
}
}
function returnResults(it) {
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
if (schemaEnv.$async) {
gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
} else {
gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
if (opts.unevaluated)
assignEvaluated(it);
gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
}
}
function assignEvaluated({ gen, evaluated, props, items }) {
if (props instanceof codegen_1.Name)
gen.assign((0, codegen_1._)`${evaluated}.props`, props);
if (items instanceof codegen_1.Name)
gen.assign((0, codegen_1._)`${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
const { gen, schema, data, allErrors, opts, self } = it;
const { RULES } = self;
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
return;
}
if (!opts.jtd)
checkStrictTypes(it, types);
gen.block(() => {
for (const group of RULES.rules)
groupKeywords(group);
groupKeywords(RULES.post);
});
function groupKeywords(group) {
if (!(0, applicability_1.shouldUseGroup)(schema, group))
return;
if (group.type) {
gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
iterateKeywords(it, group);
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else();
(0, dataType_2.reportTypeError)(it);
}
gen.endIf();
} else {
iterateKeywords(it, group);
}
if (!allErrors)
gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
}
}
function iterateKeywords(it, group) {
const { gen, schema, opts: { useDefaults } } = it;
if (useDefaults)
(0, defaults_1.assignDefaults)(it, group.type);
gen.block(() => {
for (const rule of group.rules) {
if ((0, applicability_1.shouldUseRule)(schema, rule)) {
keywordCode(it, rule.keyword, rule.definition, group.type);
}
}
});
}
function checkStrictTypes(it, types) {
if (it.schemaEnv.meta || !it.opts.strictTypes)
return;
checkContextTypes(it, types);
if (!it.opts.allowUnionTypes)
checkMultipleTypes(it, types);
checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
if (!types.length)
return;
if (!it.dataTypes.length) {
it.dataTypes = types;
return;
}
types.forEach((t) => {
if (!includesType(it.dataTypes, t)) {
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
}
});
narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
}
}
function checkKeywordTypes(it, ts) {
const rules = it.self.RULES.all;
for (const keyword in rules) {
const rule = rules[keyword];
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
const { type } = rule.definition;
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
}
}
}
}
function hasApplicableType(schTs, kwdT) {
return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
}
function includesType(ts, t) {
return ts.includes(t) || t === "integer" && ts.includes("number");
}
function narrowSchemaTypes(it, withTypes) {
const ts = [];
for (const t of it.dataTypes) {
if (includesType(withTypes, t))
ts.push(t);
else if (withTypes.includes("integer") && t === "number")
ts.push("integer");
}
it.dataTypes = ts;
}
function strictTypesError(it, msg) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
msg += ` at "${schemaPath}" (strictTypes)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
var KeywordCxt = class {
constructor(it, def, keyword) {
(0, keyword_1.validateKeywordUsage)(it, def, keyword);
this.gen = it.gen;
this.allErrors = it.allErrors;
this.keyword = keyword;
this.data = it.data;
this.schema = it.schema[keyword];
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
this.schemaType = def.schemaType;
this.parentSchema = it.schema;
this.params = {};
this.it = it;
this.def = def;
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
} else {
this.schemaCode = this.schemaValue;
if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", names_1.default.errors);
}
}
result(condition, successAction, failAction) {
this.failResult((0, codegen_1.not)(condition), successAction, failAction);
}
failResult(condition, successAction, failAction) {
this.gen.if(condition);
if (failAction)
failAction();
else
this.error();
if (successAction) {
this.gen.else();
successAction();
if (this.allErrors)
this.gen.endIf();
} else {
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
}
pass(condition, failAction) {
this.failResult((0, codegen_1.not)(condition), void 0, failAction);
}
fail(condition) {
if (condition === void 0) {
this.error();
if (!this.allErrors)
this.gen.if(false);
return;
}
this.gen.if(condition);
this.error();
if (this.allErrors)
this.gen.endIf();
else
this.gen.else();
}
fail$data(condition) {
if (!this.$data)
return this.fail(condition);
const { schemaCode } = this;
this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
}
error(append, errorParams, errorPaths) {
if (errorParams) {
this.setParams(errorParams);
this._error(append, errorPaths);
this.setParams({});
return;
}
this._error(append, errorPaths);
}
_error(append, errorPaths) {
;
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
}
$dataError() {
(0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
}
reset() {
if (this.errsCount === void 0)
throw new Error('add "trackErrors" to keyword definition');
(0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
}
ok(cond) {
if (!this.allErrors)
this.gen.if(cond);
}
setParams(obj, assign) {
if (assign)
Object.assign(this.params, obj);
else
this.params = obj;
}
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
this.gen.block(() => {
this.check$data(valid, $dataValid);
codeBlock();
});
}
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
if (!this.$data)
return;
const { gen, schemaCode, schemaType, def } = this;
gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
if (valid !== codegen_1.nil)
gen.assign(valid, true);
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data());
this.$dataError();
if (valid !== codegen_1.nil)
gen.assign(valid, false);
}
gen.else();
}
invalid$data() {
const { gen, schemaCode, schemaType, def, it } = this;
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
function wrong$DataType() {
if (schemaType.length) {
if (!(schemaCode instanceof codegen_1.Name))
throw new Error("ajv implementation error");
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
}
return codegen_1.nil;
}
function invalid$DataSchema() {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
}
return codegen_1.nil;
}
}
subschema(appl, valid) {
const subschema = (0, subschema_1.getSubschema)(this.it, appl);
(0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
(0, subschema_1.extendSubschemaMode)(subschema, appl);
const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
subschemaCode(nextContext, valid);
return nextContext;
}
mergeEvaluated(schemaCxt, toName) {
const { it, gen } = this;
if (!it.opts.unevaluated)
return;
if (it.props !== true && schemaCxt.props !== void 0) {
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
}
if (it.items !== true && schemaCxt.items !== void 0) {
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
}
}
mergeValidEvaluated(schemaCxt, valid) {
const { it, gen } = this;
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
return true;
}
}
};
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
const cxt = new KeywordCxt(it, def, keyword);
if ("code" in def) {
def.code(cxt, ruleType);
} else if (cxt.$data && def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
} else if ("macro" in def) {
(0, keyword_1.macroKeywordCode)(cxt, def);
} else if (def.compile || def.validate) {
(0, keyword_1.funcKeywordCode)(cxt, def);
}
}
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
let jsonPointer;
let data;
if ($data === "")
return names_1.default.rootData;
if ($data[0] === "/") {
if (!JSON_POINTER.test($data))
throw new Error(`Invalid JSON-pointer: ${$data}`);
jsonPointer = $data;
data = names_1.default.rootData;
} else {
const matches = RELATIVE_JSON_POINTER.exec($data);
if (!matches)
throw new Error(`Invalid JSON-pointer: ${$data}`);
const up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer === "#") {
if (up >= dataLevel)
throw new Error(errorMsg("property/index", up));
return dataPathArr[dataLevel - up];
}
if (up > dataLevel)
throw new Error(errorMsg("data", up));
data = dataNames[dataLevel - up];
if (!jsonPointer)
return data;
}
let expr = data;
const segments = jsonPointer.split("/");
for (const segment of segments) {
if (segment) {
data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
expr = (0, codegen_1._)`${expr} && ${data}`;
}
}
return expr;
function errorMsg(pointerType, up) {
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
}
}
exports.getData = getData;
}
});
// node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error = __commonJS({
"node_modules/ajv/dist/runtime/validation_error.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ValidationError = class extends Error {
constructor(errors) {
super("validation failed");
this.errors = errors;
this.ajv = this.validation = true;
}
};
exports.default = ValidationError;
}
});
// node_modules/ajv/dist/compile/ref_error.js
var require_ref_error = __commonJS({
"node_modules/ajv/dist/compile/ref_error.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var resolve_1 = require_resolve();
var MissingRefError = class extends Error {
constructor(resolver, baseId, ref, msg) {
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
}
};
exports.default = MissingRefError;
}
});
// node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
"node_modules/ajv/dist/compile/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
var codegen_1 = require_codegen();
var validation_error_1 = require_validation_error();
var names_1 = require_names();
var resolve_1 = require_resolve();
var util_1 = require_util();
var validate_1 = require_validate();
var SchemaEnv = class {
constructor(env) {
var _a;
this.refs = {};
this.dynamicAnchors = {};
let schema;
if (typeof env.schema == "object")
schema = env.schema;
this.schema = env.schema;
this.schemaId = env.schemaId;
this.root = env.root || this;
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
this.schemaPath = env.schemaPath;
this.localRefs = env.localRefs;
this.meta = env.meta;
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
this.refs = {};
}
};
exports.SchemaEnv = SchemaEnv;
function compileSchema(sch) {
const _sch = getCompilingSchema.call(this, sch);
if (_sch)
return _sch;
const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
const { es5, lines } = this.opts.code;
const { ownProperties } = this.opts;
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
let _ValidationError;
if (sch.$async) {
_ValidationError = gen.scopeValue("Error", {
ref: validation_error_1.default,
code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
});
}
const validateName = gen.scopeName("validate");
sch.validateName = validateName;
const schemaCxt = {
gen,
allErrors: this.opts.allErrors,
data: names_1.default.data,
parentData: names_1.default.parentData,
parentDataProperty: names_1.default.parentDataProperty,
dataNames: [names_1.default.data],
dataPathArr: [codegen_1.nil],
// TODO can its length be used as dataLevel if nil is removed?
dataLevel: 0,
dataTypes: [],
definedProperties: /* @__PURE__ */ new Set(),
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
validateName,
ValidationError: _ValidationError,
schema: sch.schema,
schemaEnv: sch,
rootId,
baseId: sch.baseId || rootId,
schemaPath: codegen_1.nil,
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
errorPath: (0, codegen_1._)`""`,
opts: this.opts,
self: this
};
let sourceCode;
try {
this._compilations.add(sch);
(0, validate_1.validateFunctionCode)(schemaCxt);
gen.optimize(this.opts.code.optimize);
const validateCode = gen.toString();
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
if (this.opts.code.process)
sourceCode = this.opts.code.process(sourceCode, sch);
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
const validate = makeValidate(this, this.scope.get());
this.scope.value(validateName, { ref: validate });
validate.errors = null;
validate.schema = sch.schema;
validate.schemaEnv = sch;
if (sch.$async)
validate.$async = true;
if (this.opts.code.source === true) {
validate.source = { validateName, validateCode, scopeValues: gen._values };
}
if (this.opts.unevaluated) {
const { props, items } = schemaCxt;
validate.evaluated = {
props: props instanceof codegen_1.Name ? void 0 : props,
items: items instanceof codegen_1.Name ? void 0 : items,
dynamicProps: props instanceof codegen_1.Name,
dynamicItems: items instanceof codegen_1.Name
};
if (validate.source)
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
}
sch.validate = validate;
return sch;
} catch (e) {
delete sch.validate;
delete sch.validateName;
if (sourceCode)
this.logger.error("Error compiling schema, function code:", sourceCode);
throw e;
} finally {
this._compilations.delete(sch);
}
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
var _a;
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
const schOrFunc = root.refs[ref];
if (schOrFunc)
return schOrFunc;
let _sch = resolve15.call(this, root, ref);
if (_sch === void 0) {
const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
const { schemaId } = this.opts;
if (schema)
_sch = new SchemaEnv({ schema, schemaId, root, baseId });
}
if (_sch === void 0)
return;
return root.refs[ref] = inlineOrCompile.call(this, _sch);
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
return sch.schema;
return sch.validate ? sch : compileSchema.call(this, sch);
}
function getCompilingSchema(schEnv) {
for (const sch of this._compilations) {
if (sameSchemaEnv(sch, schEnv))
return sch;
}
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
function resolve15(root, ref) {
let sch;
while (typeof (sch = this.refs[ref]) == "string")
ref = sch;
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
function resolveSchema(root, ref) {
const p = this.opts.uriResolver.parse(ref);
const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root);
}
const id = (0, resolve_1.normalizeId)(refPath);
const schOrRef = this.refs[id] || this.schemas[id];
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef);
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
return;
return getJsonPointer.call(this, p, sch);
}
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
return;
if (!schOrRef.validate)
compileSchema.call(this, schOrRef);
if (id === (0, resolve_1.normalizeId)(ref)) {
const { schema } = schOrRef;
const { schemaId } = this.opts;
const schId = schema[schemaId];
if (schId)
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
return new SchemaEnv({ schema, schemaId, root, baseId });
}
return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
"properties",
"patternProperties",
"enum",
"dependencies",
"definitions"
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
var _a;
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
return;
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean")
return;
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
if (partSchema === void 0)
return;
schema = partSchema;
const schId = typeof schema === "object" && schema[this.opts.schemaId];
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
}
}
let env;
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
env = resolveSchema.call(this, root, $ref);
}
const { schemaId } = this.opts;
env = env || new SchemaEnv({ schema, schemaId, root, baseId });
if (env.schema !== env.root.schema)
return env;
return void 0;
}
}
});
// node_modules/ajv/dist/refs/data.json
var require_data = __commonJS({
"node_modules/ajv/dist/refs/data.json"(exports, module) {
module.exports = {
$id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",
type: "object",
required: ["$data"],
properties: {
$data: {
type: "string",
anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]
}
},
additionalProperties: false
};
}
});
// node_modules/fast-uri/lib/utils.js
var require_utils = __commonJS({
"node_modules/fast-uri/lib/utils.js"(exports, module) {
"use strict";
var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u);
var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u);
var BYTE_HEX = new Array(256);
{
const HEX_DIGITS = "0123456789ABCDEF";
for (let i = 0; i < 256; i++) {
BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15];
}
}
function percentEncodeNonAscii(cp) {
if (cp < 2048) {
return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63];
}
if (cp < 65536) {
return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
}
return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
}
function stringArrayToHexStripped(input) {
let acc = "";
let code = 0;
let i = 0;
for (i = 0; i < input.length; i++) {
code = input[i].charCodeAt(0);
if (code === 48) {
continue;
}
if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
return "";
}
acc += input[i];
break;
}
for (i += 1; i < input.length; i++) {
code = input[i].charCodeAt(0);
if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
return "";
}
acc += input[i];
}
return acc;
}
var isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/);
var isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/);
var isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/);
var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
function isZoneIdentifier(zone) {
if (zone.length === 0) return false;
for (let i = 0; i < zone.length; i++) {
if (isZoneCharacter(zone[i])) continue;
if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
i += 2;
continue;
}
return false;
}
return true;
}
function compressIPv6ZeroRun(hextets) {
let bestStart = -1;
let bestLength = 0;
let runStart = -1;
let runLength = 0;
for (let i = 0; i < hextets.length; i++) {
if (hextets[i] === "0") {
if (runStart === -1) runStart = i;
runLength++;
if (runLength > bestLength) {
bestLength = runLength;
bestStart = runStart;
}
} else {
runStart = -1;
runLength = 0;
}
}
if (bestLength < 2) return hextets.join(":");
const head = hextets.slice(0, bestStart).join(":");
const tail = hextets.slice(bestStart + bestLength).join(":");
return head + "::" + tail;
}
function normalizeIPv6Address(input) {
const compression = input.indexOf("::");
if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0;
const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":");
const right = compression === -1 ? [] : input.slice(compression + 2).split(":");
if (compression !== -1) {
if (left.length === 1 && left[0] === "") left.length = 0;
if (right.length === 1 && right[0] === "") right.length = 0;
}
const parts = left.concat(right);
let hextetCount = 0;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part === "") return void 0;
if (part.indexOf(".") !== -1) {
if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0;
hextetCount += 2;
continue;
}
if (!isHextet(part)) return void 0;
parts[i] = parseInt(part, 16).toString(16);
hextetCount++;
}
if (compression === -1) {
if (hextetCount !== 8) return void 0;
return compressIPv6ZeroRun(parts);
}
if (hextetCount >= 8) return void 0;
const expanded = parts.slice(0, left.length);
for (let i = hextetCount; i < 8; i++) expanded.push("0");
for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]);
return compressIPv6ZeroRun(expanded);
}
function normalizeIPv6(host) {
const bracketed = host[0] === "[" && host[host.length - 1] === "]";
const hasBracket = host[0] === "[" || host[host.length - 1] === "]";
if (hasBracket && !bracketed) return { host, isIPV6: false, error: true };
let input = bracketed ? host.slice(1, -1) : host;
if (bracketed && isIPvFuture(input)) {
input = input.toLowerCase();
return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true };
}
if (findToken(input, ":") < 2) {
return { host, isIPV6: false, error: bracketed };
}
let zoneIdentifier = "";
const zoneSeparator = input.indexOf("%");
if (zoneSeparator !== -1) {
const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1;
zoneIdentifier = input.slice(zoneSeparator + separatorLength);
if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true };
input = input.slice(0, zoneSeparator);
}
const address = normalizeIPv6Address(input);
if (address === void 0) return { host, isIPV6: false, error: true };
return {
host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""),
escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""),
isIPV6: true
};
}
function findToken(str, token) {
let ind = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === token) ind++;
}
return ind;
}
function removeDotSegments(path) {
let input = path;
const output = [];
let nextSlash = -1;
let len = 0;
while (len = input.length) {
if (len === 1) {
if (input === ".") {
break;
} else if (input === "/") {
output.push("/");
break;
} else {
output.push(input);
break;
}
} else if (len === 2) {
if (input[0] === ".") {
if (input[1] === ".") {
break;
} else if (input[1] === "/") {
input = input.slice(2);
continue;
}
} else if (input[0] === "/") {
if (input[1] === "." || input[1] === "/") {
output.push("/");
break;
}
}
} else if (len === 3) {
if (input === "/..") {
if (output.length !== 0) {
output.pop();
}
output.push("/");
break;
}
}
if (input[0] === ".") {
if (input[1] === ".") {
if (input[2] === "/") {
input = input.slice(3);
continue;
}
} else if (input[1] === "/") {
input = input.slice(2);
continue;
}
} else if (input[0] === "/") {
if (input[1] === ".") {
if (input[2] === "/") {
input = input.slice(2);
continue;
} else if (input[2] === ".") {
if (input[3] === "/") {
input = input.slice(3);
if (output.length !== 0) {
output.pop();
}
continue;
}
}
}
}
if ((nextSlash = input.indexOf("/", 1)) === -1) {
output.push(input);
break;
} else {
output.push(input.slice(0, nextSlash));
input = input.slice(nextSlash);
}
}
return output.join("");
}
var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };
var HOST_DELIM_RE = /[@/?#:]/g;
var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
function reescapeHostDelimiters(host, isIP) {
const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
re.lastIndex = 0;
return host.replace(re, (ch) => HOST_DELIMS[ch]);
}
function normalizePercentEncoding(input, decodeUnreserved = false) {
if (input.indexOf("%") === -1) {
return input;
}
let output = "";
for (let i = 0; i < input.length; i++) {
if (input[i] === "%" && i + 2 < input.length) {
const hex = input.slice(i + 1, i + 3);
if (isHexPair(hex)) {
const normalizedHex = hex.toUpperCase();
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
if (decodeUnreserved && isUnreserved(decoded)) {
output += decoded;
} else {
output += "%" + normalizedHex;
}
i += 2;
continue;
}
}
output += input[i];
}
return output;
}
function normalizePathEncoding(input) {
let output = "";
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === "%" && i + 2 < input.length) {
const hex = input.slice(i + 1, i + 3);
if (isHexPair(hex)) {
const normalizedHex = hex.toUpperCase();
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
if (decoded !== "." && isUnreserved(decoded)) {
output += decoded;
} else {
output += "%" + normalizedHex;
}
i += 2;
continue;
}
}
if (isPathCharacter(ch)) {
output += ch;
} else {
const code = input.charCodeAt(i);
if (code < 128) {
output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
} else if (code < 55296 || code > 57343) {
output += percentEncodeNonAscii(code);
} else if (code <= 56319 && i + 1 < input.length) {
const low = input.charCodeAt(i + 1);
if (low >= 56320 && low <= 57343) {
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
i++;
} else {
output += percentEncodeNonAscii(65533);
}
} else {
output += percentEncodeNonAscii(65533);
}
}
}
return output;
}
function serializePathEncoding(input, pathNoScheme = false) {
let output = "";
let firstSegment = pathNoScheme && input[0] !== "/";
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === "%" && i + 2 < input.length) {
const hex = input.slice(i + 1, i + 3);
if (isHexPair(hex)) {
output += "%" + hex.toUpperCase();
i += 2;
continue;
}
}
if (ch === "/") {
firstSegment = false;
}
if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) {
output += ch;
} else {
const code = input.charCodeAt(i);
if (code < 128) {
output += BYTE_HEX[code];
} else if (code < 55296 || code > 57343) {
output += percentEncodeNonAscii(code);
} else if (code <= 56319 && i + 1 < input.length) {
const low = input.charCodeAt(i + 1);
if (low >= 56320 && low <= 57343) {
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
i++;
} else {
output += percentEncodeNonAscii(65533);
}
} else {
output += percentEncodeNonAscii(65533);
}
}
}
return output;
}
function encodeComponent(input, isAllowed) {
let output = "";
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === "%" && i + 2 < input.length) {
const hex = input.slice(i + 1, i + 3);
if (isHexPair(hex)) {
output += "%" + hex.toUpperCase();
i += 2;
continue;
}
}
if (isAllowed(ch)) {
output += ch;
} else {
const code = input.charCodeAt(i);
if (code < 128) {
output += BYTE_HEX[code];
} else if (code < 55296 || code > 57343) {
output += percentEncodeNonAscii(code);
} else if (code <= 56319 && i + 1 < input.length) {
const low = input.charCodeAt(i + 1);
if (low >= 56320 && low <= 57343) {
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
i++;
} else {
output += percentEncodeNonAscii(65533);
}
} else {
output += percentEncodeNonAscii(65533);
}
}
}
return output;
}
function encodeUserinfo(input) {
return encodeComponent(input, isUserinfoCharacter);
}
function encodeQuery(input) {
return encodeComponent(input, isQueryFragmentCharacter);
}
function encodeFragment(input) {
return encodeComponent(input, isQueryFragmentCharacter);
}
function isEscapeSafe(cp) {
return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95;
}
function normalizeQueryFragmentEncoding(input) {
let output = "";
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === "%" && i + 2 < input.length) {
const hex = input.slice(i + 1, i + 3);
if (isHexPair(hex)) {
const normalizedHex = hex.toUpperCase();
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
if (isUnreserved(decoded)) {
output += decoded;
} else {
output += "%" + normalizedHex;
}
i += 2;
continue;
}
}
if (isQueryFragmentCharacter(ch)) {
output += ch;
} else {
const code = input.charCodeAt(i);
if (code < 128) {
output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
} else if (code < 55296 || code > 57343) {
output += percentEncodeNonAscii(code);
} else if (code <= 56319 && i + 1 < input.length) {
const low = input.charCodeAt(i + 1);
if (low >= 56320 && low <= 57343) {
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
i++;
} else {
output += percentEncodeNonAscii(65533);
}
} else {
output += percentEncodeNonAscii(65533);
}
}
}
return output;
}
function escapePreservingEscapes(input) {
let output = "";
for (let i = 0; i < input.length; i++) {
if (input[i] === "%" && i + 2 < input.length) {
const hex = input.slice(i + 1, i + 3);
if (isHexPair(hex)) {
output += "%" + hex.toUpperCase();
i += 2;
continue;
}
}
output += escape(input[i]);
}
return output;
}
function recomposeAuthority(component) {
const uriTokens = [];
if (component.userinfo !== void 0) {
uriTokens.push(encodeUserinfo(component.userinfo));
uriTokens.push("@");
}
if (component.host !== void 0) {
let host = component.host;
if (!isIPv4(host)) {
let ipV6res = normalizeIPv6(host);
if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
host = normalizePercentEncoding(host, true);
ipV6res = normalizeIPv6(host);
}
if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
host = `[${ipV6res.escapedHost}]`;
} else {
host = reescapeHostDelimiters(host, false);
}
}
uriTokens.push(host);
}
if (typeof component.port === "number" || typeof component.port === "string") {
uriTokens.push(":");
uriTokens.push(String(component.port));
}
return uriTokens.length ? uriTokens.join("") : void 0;
}
module.exports = {
nonSimpleDomain,
recomposeAuthority,
reescapeHostDelimiters,
normalizePercentEncoding,
normalizePathEncoding,
serializePathEncoding,
normalizeQueryFragmentEncoding,
encodeUserinfo,
encodeQuery,
encodeFragment,
escapePreservingEscapes,
removeDotSegments,
isIPv4,
isUUID,
normalizeIPv6,
stringArrayToHexStripped
};
}
});
// node_modules/fast-uri/lib/schemes.js
var require_schemes = __commonJS({
"node_modules/fast-uri/lib/schemes.js"(exports, module) {
"use strict";
var { isUUID } = require_utils();
var URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu;
var supportedSchemeNames = (
/** @type {const} */
[
"http",
"https",
"ws",
"wss",
"urn",
"urn:uuid"
]
);
function isValidSchemeName(name) {
return supportedSchemeNames.indexOf(
/** @type {*} */
name
) !== -1;
}
function wsIsSecure(wsComponent) {
if (wsComponent.secure === true) {
return true;
} else if (wsComponent.secure === false) {
return false;
} else if (wsComponent.scheme) {
return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
} else {
return false;
}
}
function httpParse(component) {
if (!component.host) {
component.error = component.error || "HTTP URIs must have a host.";
}
return component;
}
function httpSerialize(component) {
const secure = String(component.scheme).toLowerCase() === "https";
if (component.port === (secure ? 443 : 80) || component.port === "") {
component.port = void 0;
}
if (!component.path) {
component.path = "/";
}
return component;
}
function wsParse(wsComponent) {
wsComponent.secure = wsIsSecure(wsComponent);
wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
wsComponent.path = void 0;
wsComponent.query = void 0;
return wsComponent;
}
function wsSerialize(wsComponent) {
if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
wsComponent.port = void 0;
}
if (typeof wsComponent.secure === "boolean") {
wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
wsComponent.secure = void 0;
}
if (wsComponent.resourceName) {
const queryIndex = wsComponent.resourceName.indexOf("?");
const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
wsComponent.path = path && path !== "/" ? path : void 0;
wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
wsComponent.resourceName = void 0;
}
wsComponent.fragment = void 0;
return wsComponent;
}
function urnParse(urnComponent, options) {
if (!urnComponent.path) {
urnComponent.error = "URN can not be parsed";
return urnComponent;
}
const matches = urnComponent.path.match(URN_REG);
if (matches && matches[0] === urnComponent.path) {
const scheme = options.scheme || urnComponent.scheme || "urn";
urnComponent.nid = matches[1].toLowerCase();
urnComponent.nss = matches[2];
const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
const schemeHandler = getSchemeHandler(urnScheme);
urnComponent.path = void 0;
if (schemeHandler) {
urnComponent = schemeHandler.parse(urnComponent, options);
}
} else {
urnComponent.error = urnComponent.error || "URN can not be parsed.";
}
return urnComponent;
}
function urnSerialize(urnComponent, options) {
if (urnComponent.nid === void 0) {
throw new Error("URN without nid cannot be serialized");
}
const scheme = options.scheme || urnComponent.scheme || "urn";
const nid = urnComponent.nid.toLowerCase();
const urnScheme = `${scheme}:${options.nid || nid}`;
const schemeHandler = getSchemeHandler(urnScheme);
if (schemeHandler) {
urnComponent = schemeHandler.serialize(urnComponent, options);
}
const uriComponent = urnComponent;
const nss = urnComponent.nss;
uriComponent.path = `${nid || options.nid}:${nss}`;
options.skipEscape = true;
return uriComponent;
}
function urnuuidParse(urnComponent, options) {
const uuidComponent = urnComponent;
uuidComponent.uuid = uuidComponent.nss;
uuidComponent.nss = void 0;
if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
uuidComponent.error = uuidComponent.error || "UUID is not valid.";
}
return uuidComponent;
}
function urnuuidSerialize(uuidComponent) {
const urnComponent = uuidComponent;
urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
return urnComponent;
}
var http = (
/** @type {SchemeHandler} */
{
scheme: "http",
domainHost: true,
parse: httpParse,
serialize: httpSerialize
}
);
var https = (
/** @type {SchemeHandler} */
{
scheme: "https",
domainHost: http.domainHost,
parse: httpParse,
serialize: httpSerialize
}
);
var ws = (
/** @type {SchemeHandler} */
{
scheme: "ws",
domainHost: true,
parse: wsParse,
serialize: wsSerialize
}
);
var wss = (
/** @type {SchemeHandler} */
{
scheme: "wss",
domainHost: ws.domainHost,
parse: ws.parse,
serialize: ws.serialize
}
);
var urn = (
/** @type {SchemeHandler} */
{
scheme: "urn",
parse: urnParse,
serialize: urnSerialize,
skipNormalize: true
}
);
var urnuuid = (
/** @type {SchemeHandler} */
{
scheme: "urn:uuid",
parse: urnuuidParse,
serialize: urnuuidSerialize,
skipNormalize: true
}
);
var SCHEMES = (
/** @type {Record<SchemeName, SchemeHandler>} */
{
http,
https,
ws,
wss,
urn,
"urn:uuid": urnuuid
}
);
Object.setPrototypeOf(SCHEMES, null);
function getSchemeHandler(scheme) {
return scheme && (SCHEMES[
/** @type {SchemeName} */
scheme
] || SCHEMES[
/** @type {SchemeName} */
scheme.toLowerCase()
]) || void 0;
}
module.exports = {
wsIsSecure,
SCHEMES,
isValidSchemeName,
getSchemeHandler
};
}
});
// node_modules/fast-uri/index.js
var require_fast_uri = __commonJS({
"node_modules/fast-uri/index.js"(exports, module) {
"use strict";
var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
var { SCHEMES, getSchemeHandler } = require_schemes();
var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
var MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
function decodeValidScheme(scheme) {
const decodedScheme = unescape(String(scheme));
if (!VALID_SCHEME.test(decodedScheme)) {
throw new TypeError(MALFORMED_SCHEME_ERROR);
}
return decodedScheme;
}
function normalize(uri, options) {
if (typeof uri === "string") {
uri = /** @type {T} */
normalizeString(uri, options);
} else if (typeof uri === "object") {
uri = /** @type {T} */
parse11(serialize(uri, options), options);
}
return uri;
}
function resolve15(baseURI, relativeURI, options) {
const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
const {
parsed: baseParsed,
malformedAuthorityOrPort: baseMalformed,
malformedPercentEncoding: baseMalformedPercentEncoding,
malformedSchemeSpecific: baseMalformedSchemeSpecific,
malformedHost: baseMalformedHost,
malformedScheme: baseMalformedScheme
} = parseWithStatus(baseURI, schemelessOptions);
const {
parsed: relativeParsed,
malformedAuthorityOrPort: relativeMalformed,
malformedPercentEncoding: relativeMalformedPercentEncoding,
malformedSchemeSpecific: relativeMalformedSchemeSpecific,
malformedHost: relativeMalformedHost,
malformedScheme: relativeMalformedScheme
} = parseWithStatus(relativeURI, schemelessOptions);
if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) {
throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
}
const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
const resolvedHost = resolved.host;
const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost);
if (resolved.error && !encodedASCIIHost) {
throw new Error(resolved.error);
}
schemelessOptions.skipEscape = true;
return serialize(resolved, schemelessOptions);
}
function resolveComponent(base, relative6, options, skipNormalization) {
const target = {};
if (!skipNormalization) {
base = parse11(serialize(base, options), options);
relative6 = parse11(serialize(relative6, options), options);
}
options = options || {};
if (!options.tolerant && relative6.scheme) {
target.scheme = relative6.scheme;
target.userinfo = relative6.userinfo;
target.host = relative6.host;
target.port = relative6.port;
target.path = removeDotSegments(relative6.path || "");
target.query = relative6.query;
} else {
if (relative6.userinfo !== void 0 || relative6.host !== void 0 || relative6.port !== void 0) {
target.userinfo = relative6.userinfo;
target.host = relative6.host;
target.port = relative6.port;
target.path = removeDotSegments(relative6.path || "");
target.query = relative6.query;
} else {
if (!relative6.path) {
target.path = base.path;
if (relative6.query !== void 0) {
target.query = relative6.query;
} else {
target.query = base.query;
}
} else {
if (relative6.path[0] === "/") {
target.path = removeDotSegments(relative6.path);
} else {
if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
target.path = "/" + relative6.path;
} else if (!base.path) {
target.path = relative6.path;
} else {
target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative6.path;
}
target.path = removeDotSegments(target.path);
}
target.query = relative6.query;
}
target.userinfo = base.userinfo;
target.host = base.host;
target.port = base.port;
}
target.scheme = base.scheme;
}
target.fragment = relative6.fragment;
return target;
}
function equal(uriA, uriB, options) {
const normalizedA = normalizeComparableURI(uriA, options);
const normalizedB = normalizeComparableURI(uriB, options);
return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB;
}
function serialize(cmpts, opts) {
const component = {
host: cmpts.host,
scheme: cmpts.scheme,
userinfo: cmpts.userinfo,
port: cmpts.port,
path: cmpts.path,
query: cmpts.query,
nid: cmpts.nid,
nss: cmpts.nss,
uuid: cmpts.uuid,
fragment: cmpts.fragment,
reference: cmpts.reference,
resourceName: cmpts.resourceName,
secure: cmpts.secure,
error: ""
};
const options = Object.assign({}, opts);
const uriTokens = [];
if (component.scheme) {
component.scheme = decodeValidScheme(component.scheme);
}
const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0;
const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority;
if (component.path !== void 0) {
if (!options.skipEscape) {
component.path = serializePathEncoding(component.path, pathNoScheme);
} else {
component.path = normalizePercentEncoding(component.path);
}
}
if (options.reference !== "suffix" && component.scheme) {
component.scheme = decodeValidScheme(component.scheme);
uriTokens.push(component.scheme, ":");
}
const authority = recomposeAuthority(component);
if (authority !== void 0) {
if (options.reference !== "suffix") {
uriTokens.push("//");
}
uriTokens.push(authority);
if (component.path && component.path[0] !== "/") {
uriTokens.push("/");
}
}
if (component.path !== void 0) {
let s = component.path;
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
s = removeDotSegments(s);
}
if (pathNoScheme) {
s = serializePathEncoding(s, true);
}
if (authority === void 0 && s[0] === "/" && s[1] === "/") {
s = "/%2F" + s.slice(2);
}
uriTokens.push(s);
}
if (component.query !== void 0) {
uriTokens.push("?", encodeQuery(component.query));
}
if (component.fragment !== void 0) {
uriTokens.push("#", encodeFragment(component.fragment));
}
return uriTokens.join("");
}
var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
function getParseError(parsed, matches) {
if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
return 'URI path must start with "/" when authority is present.';
}
if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {
return "URI port is malformed.";
}
return void 0;
}
function hasMalformedPercentEncoding(component) {
if (component === void 0) return false;
let percent = component.indexOf("%");
while (percent !== -1) {
if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
return true;
}
percent = component.indexOf("%", percent + 3);
}
return false;
}
function hasMalformedComponentPercentEncoding(matches) {
const host = matches[4];
return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !(host[0] === "[" && host[host.length - 1] === "]") && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
}
function canonicalizeHost(parsed, options, schemeHandler, isIP) {
if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && parsed.host[0] !== "[" && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
try {
parsed.host = new URL("http://" + parsed.host).hostname;
} catch (e) {
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
return true;
}
}
return false;
}
function parseWithStatus(uri, opts) {
const options = Object.assign({}, opts);
const parsed = {
scheme: void 0,
userinfo: void 0,
host: "",
port: void 0,
path: "",
query: void 0,
fragment: void 0
};
let malformedAuthorityOrPort = false;
let malformedPercentEncoding = false;
let malformedSchemeSpecific = false;
let malformedHost = false;
let malformedIPLiteral = false;
let malformedScheme = false;
let isIP = false;
if (options.reference === "suffix") {
if (options.scheme) {
uri = options.scheme + ":" + uri;
} else {
uri = "//" + uri;
}
}
const authorityMatch = uri.match(AUTHORITY_PREFIX);
if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
parsed.error = "URI authority must not contain a literal backslash.";
malformedAuthorityOrPort = true;
}
const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
if (introducerMatch !== null) {
const region = introducerMatch[1];
const normalizedRegion = region.replace(/[\t\n\r]/g, "");
if (normalizedRegion.length >= 2) {
if (normalizedRegion.slice(0, 2) !== "//") {
parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
malformedAuthorityOrPort = true;
} else if (region.length !== normalizedRegion.length) {
parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
malformedAuthorityOrPort = true;
}
}
}
const matches = uri.match(URI_PARSE);
if (matches) {
parsed.scheme = matches[1];
parsed.userinfo = matches[3];
parsed.host = matches[4];
parsed.port = parseInt(matches[5], 10);
parsed.path = matches[6] || "";
parsed.query = matches[7];
parsed.fragment = matches[8];
if (parsed.scheme !== void 0) {
const decodedScheme = unescape(parsed.scheme);
if (VALID_SCHEME.test(decodedScheme)) {
parsed.scheme = decodedScheme.toLowerCase();
} else {
parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
malformedScheme = true;
}
}
malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches);
if (malformedPercentEncoding) {
parsed.error = parsed.error || "URI contains malformed percent-encoding.";
}
if (isNaN(parsed.port)) {
parsed.port = matches[5];
}
const parseError = getParseError(parsed, matches);
if (parseError !== void 0) {
parsed.error = parsed.error || parseError;
malformedAuthorityOrPort = true;
}
if (parsed.host) {
const ipv4result = isIPv4(parsed.host);
if (ipv4result === false) {
const bracketedIPLiteral = parsed.host[0] === "[" && parsed.host[parsed.host.length - 1] === "]";
const ipv6result = normalizeIPv6(parsed.host);
isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
malformedIPLiteral = bracketedIPLiteral && ipv6result.error === true;
parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
if (malformedIPLiteral) {
parsed.error = parsed.error || "URI host is malformed.";
malformedAuthorityOrPort = true;
}
} else {
isIP = true;
}
}
if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
parsed.reference = "same-document";
} else if (parsed.scheme === void 0) {
parsed.reference = "relative";
} else if (parsed.fragment === void 0) {
parsed.reference = "absolute";
} else {
parsed.reference = "uri";
}
if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
}
const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
if (uri.indexOf("%") !== -1) {
if (parsed.host !== void 0 && !malformedIPLiteral) {
const host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
parsed.host = reescapeHostDelimiters(host, isIP);
}
}
if (parsed.path) {
parsed.path = normalizePathEncoding(parsed.path);
}
if (parsed.query) {
parsed.query = normalizeQueryFragmentEncoding(parsed.query);
}
if (parsed.fragment) {
parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment);
}
}
if (schemeHandler && schemeHandler.parse) {
schemeHandler.parse(parsed, options);
if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) {
malformedSchemeSpecific = true;
}
}
} else {
parsed.error = parsed.error || "URI can not be parsed.";
}
return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
}
function parse11(uri, opts) {
return parseWithStatus(uri, opts).parsed;
}
function normalizeString(uri, opts) {
return normalizeStringWithStatus(uri, opts).normalized;
}
function normalizeStringWithStatus(uri, opts) {
const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
return {
normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
malformedAuthorityOrPort,
malformedPercentEncoding,
malformedSchemeSpecific,
malformedHost,
malformedScheme
};
}
function normalizeComparableURI(uri, opts) {
if (typeof uri !== "string" && typeof uri !== "object") {
return void 0;
}
let value;
try {
value = typeof uri === "string" ? uri : serialize(uri, opts);
} catch {
return void 0;
}
const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts);
return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized;
}
var fastUri = {
SCHEMES,
normalize,
resolve: resolve15,
resolveComponent,
equal,
serialize,
parse: parse11
};
module.exports = fastUri;
module.exports.default = fastUri;
module.exports.fastUri = fastUri;
}
});
// node_modules/ajv/dist/runtime/uri.js
var require_uri = __commonJS({
"node_modules/ajv/dist/runtime/uri.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var uri = require_fast_uri();
uri.code = 'require("ajv/dist/runtime/uri").default';
exports.default = uri;
}
});
// node_modules/ajv/dist/core.js
var require_core = __commonJS({
"node_modules/ajv/dist/core.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require_validate();
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
return validate_1.KeywordCxt;
} });
var codegen_1 = require_codegen();
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
return codegen_1._;
} });
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
return codegen_1.str;
} });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
return codegen_1.stringify;
} });
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
return codegen_1.nil;
} });
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
return codegen_1.Name;
} });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
return codegen_1.CodeGen;
} });
var validation_error_1 = require_validation_error();
var ref_error_1 = require_ref_error();
var rules_1 = require_rules();
var compile_1 = require_compile();
var codegen_2 = require_codegen();
var resolve_1 = require_resolve();
var dataType_1 = require_dataType();
var util_1 = require_util();
var $dataRefSchema = require_data();
var uri_1 = require_uri();
var defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
"validate",
"serialize",
"parse",
"wrapper",
"root",
"schema",
"keyword",
"pattern",
"formats",
"validate$data",
"func",
"obj",
"Error"
]);
var removedOptions = {
errorDataPath: "",
format: "`validateFormats: false` can be used instead.",
nullable: '"nullable" keyword is supported by default.',
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
sourceCode: "Use option `code: {source: true}`",
strictDefaults: "It is default now, see option `strict`.",
strictKeywords: "It is default now, see option `strict`.",
uniqueItems: '"uniqueItems" keyword is always validated.',
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
cache: "Map is used as cache, schema object as key.",
serialize: "Map is used as cache, schema object as key.",
ajvErrors: "It is default now."
};
var deprecatedOptions = {
ignoreKeywordsWithRef: "",
jsPropertySyntax: "",
unicode: '"minLength"/"maxLength" account for unicode characters by default.'
};
var MAX_EXPRESSION = 200;
function requiredOptions(o) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
const s = o.strict;
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
return {
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
uriResolver
};
}
var Ajv = class {
constructor(opts = {}) {
this.schemas = {};
this.refs = {};
this.formats = /* @__PURE__ */ Object.create(null);
this._compilations = /* @__PURE__ */ new Set();
this._loading = {};
this._cache = /* @__PURE__ */ new Map();
opts = this.opts = { ...opts, ...requiredOptions(opts) };
const { es5, lines } = this.opts.code;
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
this.logger = getLogger(opts.logger);
const formatOpt = opts.validateFormats;
opts.validateFormats = false;
this.RULES = (0, rules_1.getRules)();
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
this._metaOpts = getMetaSchemaOptions.call(this);
if (opts.formats)
addInitialFormats.call(this);
this._addVocabularies();
this._addDefaultMetaSchema();
if (opts.keywords)
addInitialKeywords.call(this, opts.keywords);
if (typeof opts.meta == "object")
this.addMetaSchema(opts.meta);
addInitialSchemas.call(this);
opts.validateFormats = formatOpt;
}
_addVocabularies() {
this.addKeyword("$async");
}
_addDefaultMetaSchema() {
const { $data, meta, schemaId } = this.opts;
let _dataRefSchema = $dataRefSchema;
if (schemaId === "id") {
_dataRefSchema = { ...$dataRefSchema };
_dataRefSchema.id = _dataRefSchema.$id;
delete _dataRefSchema.$id;
}
if (meta && $data)
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
}
defaultMeta() {
const { meta, schemaId } = this.opts;
return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
}
validate(schemaKeyRef, data) {
let v;
if (typeof schemaKeyRef == "string") {
v = this.getSchema(schemaKeyRef);
if (!v)
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
} else {
v = this.compile(schemaKeyRef);
}
const valid = v(data);
if (!("$async" in v))
this.errors = v.errors;
return valid;
}
compile(schema, _meta) {
const sch = this._addSchema(schema, _meta);
return sch.validate || this._compileSchemaEnv(sch);
}
compileAsync(schema, meta) {
if (typeof this.opts.loadSchema != "function") {
throw new Error("options.loadSchema should be a function");
}
const { loadSchema } = this.opts;
return runCompileAsync.call(this, schema, meta);
async function runCompileAsync(_schema, _meta) {
await loadMetaSchema.call(this, _schema.$schema);
const sch = this._addSchema(_schema, _meta);
return sch.validate || _compileAsync.call(this, sch);
}
async function loadMetaSchema($ref) {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, { $ref }, true);
}
}
async function _compileAsync(sch) {
try {
return this._compileSchemaEnv(sch);
} catch (e) {
if (!(e instanceof ref_error_1.default))
throw e;
checkLoaded.call(this, e);
await loadMissingSchema.call(this, e.missingSchema);
return _compileAsync.call(this, sch);
}
}
function checkLoaded({ missingSchema: ref, missingRef }) {
if (this.refs[ref]) {
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
}
}
async function loadMissingSchema(ref) {
const _schema = await _loadSchema.call(this, ref);
if (!this.refs[ref])
await loadMetaSchema.call(this, _schema.$schema);
if (!this.refs[ref])
this.addSchema(_schema, ref, meta);
}
async function _loadSchema(ref) {
const p = this._loading[ref];
if (p)
return p;
try {
return await (this._loading[ref] = loadSchema(ref));
} finally {
delete this._loading[ref];
}
}
}
// Adds schema to the instance
addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
if (Array.isArray(schema)) {
for (const sch of schema)
this.addSchema(sch, void 0, _meta, _validateSchema);
return this;
}
let id;
if (typeof schema === "object") {
const { schemaId } = this.opts;
id = schema[schemaId];
if (id !== void 0 && typeof id != "string") {
throw new Error(`schema ${schemaId} must be string`);
}
}
key = (0, resolve_1.normalizeId)(key || id);
this._checkUnique(key);
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
return this;
}
// Add schema that will be used to validate other schemas
// options in META_IGNORE_OPTIONS are alway set to false
addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
this.addSchema(schema, key, true, _validateSchema);
return this;
}
// Validate schema against its meta-schema
validateSchema(schema, throwOrLogError) {
if (typeof schema == "boolean")
return true;
let $schema;
$schema = schema.$schema;
if ($schema !== void 0 && typeof $schema != "string") {
throw new Error("$schema must be a string");
}
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
if (!$schema) {
this.logger.warn("meta-schema not available");
this.errors = null;
return true;
}
const valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
const message = "schema is invalid: " + this.errorsText();
if (this.opts.validateSchema === "log")
this.logger.error(message);
else
throw new Error(message);
}
return valid;
}
// Get compiled schema by `key` or `ref`.
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
getSchema(keyRef) {
let sch;
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
keyRef = sch;
if (sch === void 0) {
const { schemaId } = this.opts;
const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
sch = compile_1.resolveSchema.call(this, root, keyRef);
if (!sch)
return;
this.refs[keyRef] = sch;
}
return sch.validate || this._compileSchemaEnv(sch);
}
// Remove cached schema(s).
// If no parameter is passed all schemas but meta-schemas are removed.
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
this._removeAllSchemas(this.schemas, schemaKeyRef);
this._removeAllSchemas(this.refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case "undefined":
this._removeAllSchemas(this.schemas);
this._removeAllSchemas(this.refs);
this._cache.clear();
return this;
case "string": {
const sch = getSchEnv.call(this, schemaKeyRef);
if (typeof sch == "object")
this._cache.delete(sch.schema);
delete this.schemas[schemaKeyRef];
delete this.refs[schemaKeyRef];
return this;
}
case "object": {
const cacheKey = schemaKeyRef;
this._cache.delete(cacheKey);
let id = schemaKeyRef[this.opts.schemaId];
if (id) {
id = (0, resolve_1.normalizeId)(id);
delete this.schemas[id];
delete this.refs[id];
}
return this;
}
default:
throw new Error("ajv.removeSchema: invalid parameter");
}
}
// add "vocabulary" - a collection of keywords
addVocabulary(definitions) {
for (const def of definitions)
this.addKeyword(def);
return this;
}
addKeyword(kwdOrDef, def) {
let keyword;
if (typeof kwdOrDef == "string") {
keyword = kwdOrDef;
if (typeof def == "object") {
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
def.keyword = keyword;
}
} else if (typeof kwdOrDef == "object" && def === void 0) {
def = kwdOrDef;
keyword = def.keyword;
if (Array.isArray(keyword) && !keyword.length) {
throw new Error("addKeywords: keyword must be string or non-empty array");
}
} else {
throw new Error("invalid addKeywords parameters");
}
checkKeyword.call(this, keyword, def);
if (!def) {
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
return this;
}
keywordMetaschema.call(this, def);
const definition = {
...def,
type: (0, dataType_1.getJSONTypes)(def.type),
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
};
(0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
return this;
}
getKeyword(keyword) {
const rule = this.RULES.all[keyword];
return typeof rule == "object" ? rule.definition : !!rule;
}
// Remove keyword
removeKeyword(keyword) {
const { RULES } = this;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
for (const group of RULES.rules) {
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
if (i >= 0)
group.rules.splice(i, 1);
}
return this;
}
// Add format
addFormat(name, format) {
if (typeof format == "string")
format = new RegExp(format);
this.formats[name] = format;
return this;
}
errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
if (!errors || errors.length === 0)
return "No errors";
return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
}
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
const rules = this.RULES.all;
metaSchema = JSON.parse(JSON.stringify(metaSchema));
for (const jsonPointer of keywordsJsonPointers) {
const segments = jsonPointer.split("/").slice(1);
let keywords = metaSchema;
for (const seg of segments)
keywords = keywords[seg];
for (const key in rules) {
const rule = rules[key];
if (typeof rule != "object")
continue;
const { $data } = rule.definition;
const schema = keywords[key];
if ($data && schema)
keywords[key] = schemaOrData(schema);
}
}
return metaSchema;
}
_removeAllSchemas(schemas, regex) {
for (const keyRef in schemas) {
const sch = schemas[keyRef];
if (!regex || regex.test(keyRef)) {
if (typeof sch == "string") {
delete schemas[keyRef];
} else if (sch && !sch.meta) {
this._cache.delete(sch.schema);
delete schemas[keyRef];
}
}
}
}
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
let id;
const { schemaId } = this.opts;
if (typeof schema == "object") {
id = schema[schemaId];
} else {
if (this.opts.jtd)
throw new Error("schema must be object");
else if (typeof schema != "boolean")
throw new Error("schema must be object or boolean");
}
let sch = this._cache.get(schema);
if (sch !== void 0)
return sch;
baseId = (0, resolve_1.normalizeId)(id || baseId);
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
this._cache.set(sch.schema, sch);
if (addSchema && !baseId.startsWith("#")) {
if (baseId)
this._checkUnique(baseId);
this.refs[baseId] = sch;
}
if (validateSchema)
this.validateSchema(schema, true);
return sch;
}
_checkUnique(id) {
if (this.schemas[id] || this.refs[id]) {
throw new Error(`schema with key or id "${id}" already exists`);
}
}
_compileSchemaEnv(sch) {
if (sch.meta)
this._compileMetaSchema(sch);
else
compile_1.compileSchema.call(this, sch);
if (!sch.validate)
throw new Error("ajv implementation error");
return sch.validate;
}
_compileMetaSchema(sch) {
const currentOpts = this.opts;
this.opts = this._metaOpts;
try {
compile_1.compileSchema.call(this, sch);
} finally {
this.opts = currentOpts;
}
}
};
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
for (const key in checkOpts) {
const opt = key;
if (opt in options)
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
}
}
function getSchEnv(keyRef) {
keyRef = (0, resolve_1.normalizeId)(keyRef);
return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
const optsSchemas = this.opts.schemas;
if (!optsSchemas)
return;
if (Array.isArray(optsSchemas))
this.addSchema(optsSchemas);
else
for (const key in optsSchemas)
this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
for (const name in this.opts.formats) {
const format = this.opts.formats[name];
if (format)
this.addFormat(name, format);
}
}
function addInitialKeywords(defs) {
if (Array.isArray(defs)) {
this.addVocabulary(defs);
return;
}
this.logger.warn("keywords option as map is deprecated, pass array");
for (const keyword in defs) {
const def = defs[keyword];
if (!def.keyword)
def.keyword = keyword;
this.addKeyword(def);
}
}
function getMetaSchemaOptions() {
const metaOpts = { ...this.opts };
for (const opt of META_IGNORE_OPTIONS)
delete metaOpts[opt];
return metaOpts;
}
var noLogs = { log() {
}, warn() {
}, error() {
} };
function getLogger(logger) {
if (logger === false)
return noLogs;
if (logger === void 0)
return console;
if (logger.log && logger.warn && logger.error)
return logger;
throw new Error("logger must implement log, warn and error methods");
}
var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
const { RULES } = this;
(0, util_1.eachItem)(keyword, (kwd) => {
if (RULES.keywords[kwd])
throw new Error(`Keyword ${kwd} is already defined`);
if (!KEYWORD_NAME.test(kwd))
throw new Error(`Keyword ${kwd} has invalid name`);
});
if (!def)
return;
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function');
}
}
function addRule(keyword, definition, dataType) {
var _a;
const post = definition === null || definition === void 0 ? void 0 : definition.post;
if (dataType && post)
throw new Error('keyword with "post" flag cannot have "type"');
const { RULES } = this;
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.rules.push(ruleGroup);
}
RULES.keywords[keyword] = true;
if (!definition)
return;
const rule = {
keyword,
definition: {
...definition,
type: (0, dataType_1.getJSONTypes)(definition.type),
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
}
};
if (definition.before)
addBeforeRule.call(this, ruleGroup, rule, definition.before);
else
ruleGroup.rules.push(rule);
RULES.all[keyword] = rule;
(_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule);
} else {
ruleGroup.rules.push(rule);
this.logger.warn(`rule ${before} is not defined`);
}
}
function keywordMetaschema(def) {
let { metaSchema } = def;
if (metaSchema === void 0)
return;
if (def.$data && this.opts.$data)
metaSchema = schemaOrData(metaSchema);
def.validateSchema = this.compile(metaSchema, true);
}
var $dataRef = {
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
};
function schemaOrData(schema) {
return { anyOf: [schema, $dataRef] };
}
}
});
// node_modules/ajv/dist/vocabularies/core/id.js
var require_id = __commonJS({
"node_modules/ajv/dist/vocabularies/core/id.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var def = {
keyword: "id",
code() {
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref = __commonJS({
"node_modules/ajv/dist/vocabularies/core/ref.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callRef = exports.getValidate = void 0;
var ref_error_1 = require_ref_error();
var code_1 = require_code2();
var codegen_1 = require_codegen();
var names_1 = require_names();
var compile_1 = require_compile();
var util_1 = require_util();
var def = {
keyword: "$ref",
schemaType: "string",
code(cxt) {
const { gen, schema: $ref, it } = cxt;
const { baseId, schemaEnv: env, validateName, opts, self } = it;
const { root } = env;
if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
return callRootRef();
const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
if (schOrEnv === void 0)
throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
if (schOrEnv instanceof compile_1.SchemaEnv)
return callValidate(schOrEnv);
return inlineRefSchema(schOrEnv);
function callRootRef() {
if (env === root)
return callRef(cxt, validateName, env, env.$async);
const rootName = gen.scopeValue("root", { ref: root });
return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
}
function callValidate(sch) {
const v = getValidate(cxt, sch);
callRef(cxt, v, sch, sch.$async);
}
function inlineRefSchema(sch) {
const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
const valid = gen.name("valid");
const schCxt = cxt.subschema({
schema: sch,
dataTypes: [],
schemaPath: codegen_1.nil,
topSchemaRef: schName,
errSchemaPath: $ref
}, valid);
cxt.mergeEvaluated(schCxt);
cxt.ok(valid);
}
}
};
function getValidate(cxt, sch) {
const { gen } = cxt;
return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
const { gen, it } = cxt;
const { allErrors, schemaEnv: env, opts } = it;
const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
if ($async)
callAsyncRef();
else
callSyncRef();
function callAsyncRef() {
if (!env.$async)
throw new Error("async schema referenced by sync schema");
const valid = gen.let("valid");
gen.try(() => {
gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
addEvaluatedFrom(v);
if (!allErrors)
gen.assign(valid, true);
}, (e) => {
gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
addErrorsFrom(e);
if (!allErrors)
gen.assign(valid, false);
});
cxt.ok(valid);
}
function callSyncRef() {
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
}
function addErrorsFrom(source) {
const errs = (0, codegen_1._)`${source}.errors`;
gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
}
function addEvaluatedFrom(source) {
var _a;
if (!it.opts.unevaluated)
return;
const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
if (it.props !== true) {
if (schEvaluated && !schEvaluated.dynamicProps) {
if (schEvaluated.props !== void 0) {
it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
}
} else {
const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
}
}
if (it.items !== true) {
if (schEvaluated && !schEvaluated.dynamicItems) {
if (schEvaluated.items !== void 0) {
it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
}
} else {
const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
}
}
}
}
exports.callRef = callRef;
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/core/index.js
var require_core2 = __commonJS({
"node_modules/ajv/dist/vocabularies/core/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var id_1 = require_id();
var ref_1 = require_ref();
var core = [
"$schema",
"$id",
"$defs",
"$vocabulary",
{ keyword: "$comment" },
"definitions",
id_1.default,
ref_1.default
];
exports.default = core;
}
});
// node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var ops = codegen_1.operators;
var KWDs = {
maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
};
var error = {
message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
};
var def = {
keyword: Object.keys(KWDs),
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var error = {
message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
};
var def = {
keyword: "multipleOf",
type: "number",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { gen, data, schemaCode, it } = cxt;
const prec = it.opts.multipleOfPrecision;
const res = gen.let("res");
const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length = __commonJS({
"node_modules/ajv/dist/runtime/ucs2length.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function ucs2length(str) {
const len = str.length;
let length = 0;
let pos = 0;
let value;
while (pos < len) {
length++;
value = str.charCodeAt(pos++);
if (value >= 55296 && value <= 56319 && pos < len) {
value = str.charCodeAt(pos);
if ((value & 64512) === 56320)
pos++;
}
}
return length;
}
exports.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
}
});
// node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var ucs2length_1 = require_ucs2length();
var error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxLength" ? "more" : "fewer";
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
},
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
};
var def = {
keyword: ["maxLength", "minLength"],
type: "string",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode, it } = cxt;
const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var code_1 = require_code2();
var util_1 = require_util();
var codegen_1 = require_codegen();
var error = {
message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
};
var def = {
keyword: "pattern",
type: "string",
schemaType: "string",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
const u = it.opts.unicodeRegExp ? "u" : "";
if ($data) {
const { regExp } = it.opts.code;
const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
const valid = gen.let("valid");
gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
cxt.fail$data((0, codegen_1._)`!${valid}`);
} else {
const regExp = (0, code_1.usePattern)(cxt, schema);
cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxProperties" ? "more" : "fewer";
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
},
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
};
var def = {
keyword: ["maxProperties", "minProperties"],
type: "object",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/required.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var code_1 = require_code2();
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
};
var def = {
keyword: "required",
type: "object",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, schema, schemaCode, data, $data, it } = cxt;
const { opts } = it;
if (!$data && schema.length === 0)
return;
const useLoop = schema.length >= opts.loopRequired;
if (it.allErrors)
allErrorsMode();
else
exitOnErrorMode();
if (opts.strictRequired) {
const props = cxt.parentSchema.properties;
const { definedProperties } = cxt.it;
for (const requiredKey of schema) {
if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
(0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
}
}
}
function allErrorsMode() {
if (useLoop || $data) {
cxt.block$data(codegen_1.nil, loopAllRequired);
} else {
for (const prop of schema) {
(0, code_1.checkReportMissingProp)(cxt, prop);
}
}
}
function exitOnErrorMode() {
const missing = gen.let("missing");
if (useLoop || $data) {
const valid = gen.let("valid", true);
cxt.block$data(valid, () => loopUntilMissing(missing, valid));
cxt.ok(valid);
} else {
gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
function loopAllRequired() {
gen.forOf("prop", schemaCode, (prop) => {
cxt.setParams({ missingProperty: prop });
gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
});
}
function loopUntilMissing(missing, valid) {
cxt.setParams({ missingProperty: missing });
gen.forOf(missing, schemaCode, () => {
gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
gen.if((0, codegen_1.not)(valid), () => {
cxt.error();
gen.break();
});
}, codegen_1.nil);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var error = {
message({ keyword, schemaCode }) {
const comp = keyword === "maxItems" ? "more" : "fewer";
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
},
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
};
var def = {
keyword: ["maxItems", "minItems"],
type: "array",
schemaType: "number",
$data: true,
error,
code(cxt) {
const { keyword, data, schemaCode } = cxt;
const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/runtime/equal.js
var require_equal = __commonJS({
"node_modules/ajv/dist/runtime/equal.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var equal = require_fast_deep_equal();
equal.code = 'require("ajv/dist/runtime/equal").default';
exports.default = equal;
}
});
// node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dataType_1 = require_dataType();
var codegen_1 = require_codegen();
var util_1 = require_util();
var equal_1 = require_equal();
var error = {
message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
};
var def = {
keyword: "uniqueItems",
type: "array",
schemaType: "boolean",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
if (!$data && !schema)
return;
const valid = gen.let("valid");
const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
cxt.ok(valid);
function validateUniqueItems() {
const i = gen.let("i", (0, codegen_1._)`${data}.length`);
const j = gen.let("j");
cxt.setParams({ i, j });
gen.assign(valid, true);
gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
}
function canOptimize() {
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
}
function loopN(i, j) {
const item = gen.name("item");
const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
const indices = gen.const("indices", (0, codegen_1._)`{}`);
gen.for((0, codegen_1._)`;${i}--;`, () => {
gen.let(item, (0, codegen_1._)`${data}[${i}]`);
gen.if(wrongType, (0, codegen_1._)`continue`);
if (itemTypes.length > 1)
gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
cxt.error();
gen.assign(valid, false).break();
}).code((0, codegen_1._)`${indices}[${item}] = ${i}`);
});
}
function loopN2(i, j) {
const eql = (0, util_1.useFunc)(gen, equal_1.default);
const outer = gen.name("outer");
gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
cxt.error();
gen.assign(valid, false).break(outer);
})));
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/const.js
var require_const = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/const.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var equal_1 = require_equal();
var error = {
message: "must be equal to constant",
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
};
var def = {
keyword: "const",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schemaCode, schema } = cxt;
if ($data || schema && typeof schema == "object") {
cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
} else {
cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var equal_1 = require_equal();
var error = {
message: "must be equal to one of the allowed values",
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
};
var def = {
keyword: "enum",
schemaType: "array",
$data: true,
error,
code(cxt) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
if (!$data && schema.length === 0)
throw new Error("enum must have non-empty array");
const useLoop = schema.length >= it.opts.loopEnum;
let eql;
const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
let valid;
if (useLoop || $data) {
valid = gen.let("valid");
cxt.block$data(valid, loopEnum);
} else {
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const vSchema = gen.const("vSchema", schemaCode);
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
}
cxt.pass(valid);
function loopEnum() {
gen.assign(valid, false);
gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
}
function equalCode(vSchema, i) {
const sch = schema[i];
return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var limitNumber_1 = require_limitNumber();
var multipleOf_1 = require_multipleOf();
var limitLength_1 = require_limitLength();
var pattern_1 = require_pattern();
var limitProperties_1 = require_limitProperties();
var required_1 = require_required();
var limitItems_1 = require_limitItems();
var uniqueItems_1 = require_uniqueItems();
var const_1 = require_const();
var enum_1 = require_enum();
var validation = [
// number
limitNumber_1.default,
multipleOf_1.default,
// string
limitLength_1.default,
pattern_1.default,
// object
limitProperties_1.default,
required_1.default,
// array
limitItems_1.default,
uniqueItems_1.default,
// any
{ keyword: "type", schemaType: ["string", "array"] },
{ keyword: "nullable", schemaType: "boolean" },
const_1.default,
enum_1.default
];
exports.default = validation;
}
});
// node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAdditionalItems = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
};
var def = {
keyword: "additionalItems",
type: "array",
schemaType: ["boolean", "object"],
before: "uniqueItems",
error,
code(cxt) {
const { parentSchema, it } = cxt;
const { items } = parentSchema;
if (!Array.isArray(items)) {
(0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
return;
}
validateAdditionalItems(cxt, items);
}
};
function validateAdditionalItems(cxt, items) {
const { gen, schema, data, keyword, it } = cxt;
it.items = true;
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
if (schema === false) {
cxt.setParams({ len: items.length });
cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
} else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
cxt.ok(valid);
}
function validateItems(valid) {
gen.forRange("i", items.length, len, (i) => {
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
if (!it.allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
});
}
}
exports.validateAdditionalItems = validateAdditionalItems;
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTuple = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
var code_1 = require_code2();
var def = {
keyword: "items",
type: "array",
schemaType: ["object", "array", "boolean"],
before: "uniqueItems",
code(cxt) {
const { schema, it } = cxt;
if (Array.isArray(schema))
return validateTuple(cxt, "additionalItems", schema);
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
cxt.ok((0, code_1.validateArray)(cxt));
}
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
const { gen, parentSchema, data, keyword, it } = cxt;
checkStrictTuple(parentSchema);
if (it.opts.unevaluated && schArr.length && it.items !== true) {
it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
}
const valid = gen.name("valid");
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
schArr.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
keyword,
schemaProp: i,
dataProp: i
}, valid));
cxt.ok(valid);
});
function checkStrictTuple(sch) {
const { opts, errSchemaPath } = it;
const l = schArr.length;
const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
if (opts.strictTuples && !fullTuple) {
const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
(0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
}
}
}
exports.validateTuple = validateTuple;
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var items_1 = require_items();
var def = {
keyword: "prefixItems",
type: "array",
schemaType: ["array"],
before: "uniqueItems",
code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items2020 = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var code_1 = require_code2();
var additionalItems_1 = require_additionalItems();
var error = {
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
};
var def = {
keyword: "items",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
error,
code(cxt) {
const { schema, parentSchema, it } = cxt;
const { prefixItems } = parentSchema;
it.items = true;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
if (prefixItems)
(0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
else
cxt.ok((0, code_1.validateArray)(cxt));
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
};
var def = {
keyword: "contains",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
let min;
let max;
const { minContains, maxContains } = parentSchema;
if (it.opts.next) {
min = minContains === void 0 ? 1 : minContains;
max = maxContains;
} else {
min = 1;
}
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
cxt.setParams({ min, max });
if (max === void 0 && min === 0) {
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
return;
}
if (max !== void 0 && min > max) {
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
cxt.fail();
return;
}
if ((0, util_1.alwaysValidSchema)(it, schema)) {
let cond = (0, codegen_1._)`${len} >= ${min}`;
if (max !== void 0)
cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
cxt.pass(cond);
return;
}
it.items = true;
const valid = gen.name("valid");
if (max === void 0 && min === 1) {
validateItems(valid, () => gen.if(valid, () => gen.break()));
} else if (min === 0) {
gen.let(valid, true);
if (max !== void 0)
gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
} else {
gen.let(valid, false);
validateItemsWithCount();
}
cxt.result(valid, () => cxt.reset());
function validateItemsWithCount() {
const schValid = gen.name("_valid");
const count = gen.let("count", 0);
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
}
function validateItems(_valid, block) {
gen.forRange("i", 0, len, (i) => {
cxt.subschema({
keyword: "contains",
dataProp: i,
dataPropType: util_1.Type.Num,
compositeRule: true
}, _valid);
block();
});
}
function checkLimits(count) {
gen.code((0, codegen_1._)`${count}++`);
if (max === void 0) {
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
} else {
gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
if (min === 1)
gen.assign(valid, true);
else
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
}
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
var codegen_1 = require_codegen();
var util_1 = require_util();
var code_1 = require_code2();
exports.error = {
message: ({ params: { property, depsCount, deps } }) => {
const property_ies = depsCount === 1 ? "property" : "properties";
return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
},
params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
missingProperty: ${missingProperty},
depsCount: ${depsCount},
deps: ${deps}}`
// TODO change to reference
};
var def = {
keyword: "dependencies",
type: "object",
schemaType: "object",
error: exports.error,
code(cxt) {
const [propDeps, schDeps] = splitDependencies(cxt);
validatePropertyDeps(cxt, propDeps);
validateSchemaDeps(cxt, schDeps);
}
};
function splitDependencies({ schema }) {
const propertyDeps = {};
const schemaDeps = {};
for (const key in schema) {
if (key === "__proto__")
continue;
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
deps[key] = schema[key];
}
return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
const { gen, data, it } = cxt;
if (Object.keys(propertyDeps).length === 0)
return;
const missing = gen.let("missing");
for (const prop in propertyDeps) {
const deps = propertyDeps[prop];
if (deps.length === 0)
continue;
const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
cxt.setParams({
property: prop,
depsCount: deps.length,
deps: deps.join(", ")
});
if (it.allErrors) {
gen.if(hasProperty, () => {
for (const depProp of deps) {
(0, code_1.checkReportMissingProp)(cxt, depProp);
}
});
} else {
gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
(0, code_1.reportMissingProp)(cxt, missing);
gen.else();
}
}
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
const { gen, data, keyword, it } = cxt;
const valid = gen.name("valid");
for (const prop in schemaDeps) {
if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
continue;
gen.if(
(0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),
() => {
const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
cxt.mergeValidEvaluated(schCxt, valid);
},
() => gen.var(valid, true)
// TODO var
);
cxt.ok(valid);
}
}
exports.validateSchemaDeps = validateSchemaDeps;
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: "property name must be valid",
params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
};
var def = {
keyword: "propertyNames",
type: "object",
schemaType: ["object", "boolean"],
error,
code(cxt) {
const { gen, schema, data, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const valid = gen.name("valid");
gen.forIn("key", data, (key) => {
cxt.setParams({ propertyName: key });
cxt.subschema({
keyword: "propertyNames",
data: key,
dataTypes: ["string"],
propertyName: key,
compositeRule: true
}, valid);
gen.if((0, codegen_1.not)(valid), () => {
cxt.error(true);
if (!it.allErrors)
gen.break();
});
});
cxt.ok(valid);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var code_1 = require_code2();
var codegen_1 = require_codegen();
var names_1 = require_names();
var util_1 = require_util();
var error = {
message: "must NOT have additional properties",
params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
};
var def = {
keyword: "additionalProperties",
type: ["object"],
schemaType: ["boolean", "object"],
allowUndefined: true,
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, data, errsCount, it } = cxt;
if (!errsCount)
throw new Error("ajv implementation error");
const { allErrors, opts } = it;
it.props = true;
if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
return;
const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
checkAdditionalProperties();
cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
function checkAdditionalProperties() {
gen.forIn("key", data, (key) => {
if (!props.length && !patProps.length)
additionalPropertyCode(key);
else
gen.if(isAdditional(key), () => additionalPropertyCode(key));
});
}
function isAdditional(key) {
let definedProp;
if (props.length > 8) {
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
} else if (props.length) {
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
} else {
definedProp = codegen_1.nil;
}
if (patProps.length) {
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
}
return (0, codegen_1.not)(definedProp);
}
function deleteAdditional(key) {
gen.code((0, codegen_1._)`delete ${data}[${key}]`);
}
function additionalPropertyCode(key) {
if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
deleteAdditional(key);
return;
}
if (schema === false) {
cxt.setParams({ additionalProperty: key });
cxt.error();
if (!allErrors)
gen.break();
return;
}
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.name("valid");
if (opts.removeAdditional === "failing") {
applyAdditionalSchema(key, valid, false);
gen.if((0, codegen_1.not)(valid), () => {
cxt.reset();
deleteAdditional(key);
});
} else {
applyAdditionalSchema(key, valid);
if (!allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
}
}
function applyAdditionalSchema(key, valid, errors) {
const subschema = {
keyword: "additionalProperties",
dataProp: key,
dataPropType: util_1.Type.Str
};
if (errors === false) {
Object.assign(subschema, {
compositeRule: true,
createErrors: false,
allErrors: false
});
}
cxt.subschema(subschema, valid);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var validate_1 = require_validate();
var code_1 = require_code2();
var util_1 = require_util();
var additionalProperties_1 = require_additionalProperties();
var def = {
keyword: "properties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, parentSchema, data, it } = cxt;
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
}
const allProps = (0, code_1.allSchemaProperties)(schema);
for (const prop of allProps) {
it.definedProperties.add(prop);
}
if (it.opts.unevaluated && allProps.length && it.props !== true) {
it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
}
const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
if (properties.length === 0)
return;
const valid = gen.name("valid");
for (const prop of properties) {
if (hasDefault(prop)) {
applyPropertySchema(prop);
} else {
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
applyPropertySchema(prop);
if (!it.allErrors)
gen.else().var(valid, true);
gen.endIf();
}
cxt.it.definedProperties.add(prop);
cxt.ok(valid);
}
function hasDefault(prop) {
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
}
function applyPropertySchema(prop) {
cxt.subschema({
keyword: "properties",
schemaProp: prop,
dataProp: prop
}, valid);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
var require_patternProperties = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var code_1 = require_code2();
var codegen_1 = require_codegen();
var util_1 = require_util();
var util_2 = require_util();
var def = {
keyword: "patternProperties",
type: "object",
schemaType: "object",
code(cxt) {
const { gen, schema, data, parentSchema, it } = cxt;
const { opts } = it;
const patterns = (0, code_1.allSchemaProperties)(schema);
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
return;
}
const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
const valid = gen.name("valid");
if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
}
const { props } = it;
validatePatternProperties();
function validatePatternProperties() {
for (const pat of patterns) {
if (checkProperties)
checkMatchingProperties(pat);
if (it.allErrors) {
validateProperties(pat);
} else {
gen.var(valid, true);
validateProperties(pat);
gen.if(valid);
}
}
}
function checkMatchingProperties(pat) {
for (const prop in checkProperties) {
if (new RegExp(pat).test(prop)) {
(0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
}
}
}
function validateProperties(pat) {
gen.forIn("key", data, (key) => {
gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
const alwaysValid = alwaysValidPatterns.includes(pat);
if (!alwaysValid) {
cxt.subschema({
keyword: "patternProperties",
schemaProp: pat,
dataProp: key,
dataPropType: util_2.Type.Str
}, valid);
}
if (it.opts.unevaluated && props !== true) {
gen.assign((0, codegen_1._)`${props}[${key}]`, true);
} else if (!alwaysValid && !it.allErrors) {
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
});
});
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require_util();
var def = {
keyword: "not",
schemaType: ["object", "boolean"],
trackErrors: true,
code(cxt) {
const { gen, schema, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema)) {
cxt.fail();
return;
}
const valid = gen.name("valid");
cxt.subschema({
keyword: "not",
compositeRule: true,
createErrors: false,
allErrors: false
}, valid);
cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
},
error: { message: "must NOT be valid" }
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/anyOf.js
var require_anyOf = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var code_1 = require_code2();
var def = {
keyword: "anyOf",
schemaType: "array",
trackErrors: true,
code: code_1.validateUnion,
error: { message: "must match a schema in anyOf" }
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: "must match exactly one schema in oneOf",
params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
};
var def = {
keyword: "oneOf",
schemaType: "array",
trackErrors: true,
error,
code(cxt) {
const { gen, schema, parentSchema, it } = cxt;
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
if (it.opts.discriminator && parentSchema.discriminator)
return;
const schArr = schema;
const valid = gen.let("valid", false);
const passing = gen.let("passing", null);
const schValid = gen.name("_valid");
cxt.setParams({ passing });
gen.block(validateOneOf);
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
function validateOneOf() {
schArr.forEach((sch, i) => {
let schCxt;
if ((0, util_1.alwaysValidSchema)(it, sch)) {
gen.var(schValid, true);
} else {
schCxt = cxt.subschema({
keyword: "oneOf",
schemaProp: i,
compositeRule: true
}, schValid);
}
if (i > 0) {
gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
}
gen.if(schValid, () => {
gen.assign(valid, true);
gen.assign(passing, i);
if (schCxt)
cxt.mergeEvaluated(schCxt, codegen_1.Name);
});
});
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/allOf.js
var require_allOf = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require_util();
var def = {
keyword: "allOf",
schemaType: "array",
code(cxt) {
const { gen, schema, it } = cxt;
if (!Array.isArray(schema))
throw new Error("ajv implementation error");
const valid = gen.name("valid");
schema.forEach((sch, i) => {
if ((0, util_1.alwaysValidSchema)(it, sch))
return;
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
cxt.ok(valid);
cxt.mergeEvaluated(schCxt);
});
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
};
var def = {
keyword: "if",
schemaType: ["object", "boolean"],
trackErrors: true,
error,
code(cxt) {
const { gen, parentSchema, it } = cxt;
if (parentSchema.then === void 0 && parentSchema.else === void 0) {
(0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
}
const hasThen = hasSchema(it, "then");
const hasElse = hasSchema(it, "else");
if (!hasThen && !hasElse)
return;
const valid = gen.let("valid", true);
const schValid = gen.name("_valid");
validateIf();
cxt.reset();
if (hasThen && hasElse) {
const ifClause = gen.let("ifClause");
cxt.setParams({ ifClause });
gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
} else if (hasThen) {
gen.if(schValid, validateClause("then"));
} else {
gen.if((0, codegen_1.not)(schValid), validateClause("else"));
}
cxt.pass(valid, () => cxt.error(true));
function validateIf() {
const schCxt = cxt.subschema({
keyword: "if",
compositeRule: true,
createErrors: false,
allErrors: false
}, schValid);
cxt.mergeEvaluated(schCxt);
}
function validateClause(keyword, ifClause) {
return () => {
const schCxt = cxt.subschema({ keyword }, schValid);
gen.assign(valid, schValid);
cxt.mergeValidEvaluated(schCxt, valid);
if (ifClause)
gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
else
cxt.setParams({ ifClause: keyword });
};
}
}
};
function hasSchema(it, keyword) {
const schema = it.schema[keyword];
return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require_util();
var def = {
keyword: ["then", "else"],
schemaType: ["object", "boolean"],
code({ keyword, parentSchema, it }) {
if (parentSchema.if === void 0)
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var additionalItems_1 = require_additionalItems();
var prefixItems_1 = require_prefixItems();
var items_1 = require_items();
var items2020_1 = require_items2020();
var contains_1 = require_contains();
var dependencies_1 = require_dependencies();
var propertyNames_1 = require_propertyNames();
var additionalProperties_1 = require_additionalProperties();
var properties_1 = require_properties();
var patternProperties_1 = require_patternProperties();
var not_1 = require_not();
var anyOf_1 = require_anyOf();
var oneOf_1 = require_oneOf();
var allOf_1 = require_allOf();
var if_1 = require_if();
var thenElse_1 = require_thenElse();
function getApplicator(draft2020 = false) {
const applicator = [
// any
not_1.default,
anyOf_1.default,
oneOf_1.default,
allOf_1.default,
if_1.default,
thenElse_1.default,
// object
propertyNames_1.default,
additionalProperties_1.default,
dependencies_1.default,
properties_1.default,
patternProperties_1.default
];
if (draft2020)
applicator.push(prefixItems_1.default, items2020_1.default);
else
applicator.push(additionalItems_1.default, items_1.default);
applicator.push(contains_1.default);
return applicator;
}
exports.default = getApplicator;
}
});
// node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js
var require_dynamicAnchor = __commonJS({
"node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicAnchor = void 0;
var codegen_1 = require_codegen();
var names_1 = require_names();
var compile_1 = require_compile();
var ref_1 = require_ref();
var def = {
keyword: "$dynamicAnchor",
schemaType: "string",
code: (cxt) => dynamicAnchor(cxt, cxt.schema)
};
function dynamicAnchor(cxt, anchor) {
const { gen, it } = cxt;
it.schemaEnv.root.dynamicAnchors[anchor] = true;
const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt);
gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate));
}
exports.dynamicAnchor = dynamicAnchor;
function _getValidate(cxt) {
const { schemaEnv, schema, self } = cxt.it;
const { root, baseId, localRefs, meta } = schemaEnv.root;
const { schemaId } = self.opts;
const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
compile_1.compileSchema.call(self, sch);
return (0, ref_1.getValidate)(cxt, sch);
}
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js
var require_dynamicRef = __commonJS({
"node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicRef = void 0;
var codegen_1 = require_codegen();
var names_1 = require_names();
var ref_1 = require_ref();
var def = {
keyword: "$dynamicRef",
schemaType: "string",
code: (cxt) => dynamicRef(cxt, cxt.schema)
};
function dynamicRef(cxt, ref) {
const { gen, keyword, it } = cxt;
if (ref[0] !== "#")
throw new Error(`"${keyword}" only supports hash fragment reference`);
const anchor = ref.slice(1);
if (it.allErrors) {
_dynamicRef();
} else {
const valid = gen.let("valid", false);
_dynamicRef(valid);
cxt.ok(valid);
}
function _dynamicRef(valid) {
if (it.schemaEnv.root.dynamicAnchors[anchor]) {
const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));
} else {
_callRef(it.validateName, valid)();
}
}
function _callRef(validate, valid) {
return valid ? () => gen.block(() => {
(0, ref_1.callRef)(cxt, validate);
gen.let(valid, true);
}) : () => (0, ref_1.callRef)(cxt, validate);
}
}
exports.dynamicRef = dynamicRef;
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js
var require_recursiveAnchor = __commonJS({
"node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dynamicAnchor_1 = require_dynamicAnchor();
var util_1 = require_util();
var def = {
keyword: "$recursiveAnchor",
schemaType: "boolean",
code(cxt) {
if (cxt.schema)
(0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
else
(0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js
var require_recursiveRef = __commonJS({
"node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dynamicRef_1 = require_dynamicRef();
var def = {
keyword: "$recursiveRef",
schemaType: "string",
code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema)
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/dynamic/index.js
var require_dynamic = __commonJS({
"node_modules/ajv/dist/vocabularies/dynamic/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dynamicAnchor_1 = require_dynamicAnchor();
var dynamicRef_1 = require_dynamicRef();
var recursiveAnchor_1 = require_recursiveAnchor();
var recursiveRef_1 = require_recursiveRef();
var dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
exports.default = dynamic;
}
});
// node_modules/ajv/dist/vocabularies/validation/dependentRequired.js
var require_dependentRequired = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/dependentRequired.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dependencies_1 = require_dependencies();
var def = {
keyword: "dependentRequired",
type: "object",
schemaType: "object",
error: dependencies_1.error,
code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt)
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js
var require_dependentSchemas = __commonJS({
"node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dependencies_1 = require_dependencies();
var def = {
keyword: "dependentSchemas",
type: "object",
schemaType: "object",
code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt)
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/validation/limitContains.js
var require_limitContains = __commonJS({
"node_modules/ajv/dist/vocabularies/validation/limitContains.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require_util();
var def = {
keyword: ["maxContains", "minContains"],
type: "array",
schemaType: "number",
code({ keyword, parentSchema, it }) {
if (parentSchema.contains === void 0) {
(0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/next.js
var require_next = __commonJS({
"node_modules/ajv/dist/vocabularies/next.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dependentRequired_1 = require_dependentRequired();
var dependentSchemas_1 = require_dependentSchemas();
var limitContains_1 = require_limitContains();
var next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
exports.default = next;
}
});
// node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js
var require_unevaluatedProperties = __commonJS({
"node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var names_1 = require_names();
var error = {
message: "must NOT have unevaluated properties",
params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`
};
var def = {
keyword: "unevaluatedProperties",
type: "object",
schemaType: ["boolean", "object"],
trackErrors: true,
error,
code(cxt) {
const { gen, schema, data, errsCount, it } = cxt;
if (!errsCount)
throw new Error("ajv implementation error");
const { allErrors, props } = it;
if (props instanceof codegen_1.Name) {
gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
} else if (props !== true) {
gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
}
it.props = true;
cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
function unevaluatedPropCode(key) {
if (schema === false) {
cxt.setParams({ unevaluatedProperty: key });
cxt.error();
if (!allErrors)
gen.break();
return;
}
if (!(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.name("valid");
cxt.subschema({
keyword: "unevaluatedProperties",
dataProp: key,
dataPropType: util_1.Type.Str
}, valid);
if (!allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
}
}
function unevaluatedDynamic(evaluatedProps, key) {
return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`;
}
function unevaluatedStatic(evaluatedProps, key) {
const ps = [];
for (const p in evaluatedProps) {
if (evaluatedProps[p] === true)
ps.push((0, codegen_1._)`${key} !== ${p}`);
}
return (0, codegen_1.and)(...ps);
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js
var require_unevaluatedItems = __commonJS({
"node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var util_1 = require_util();
var error = {
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
};
var def = {
keyword: "unevaluatedItems",
type: "array",
schemaType: ["boolean", "object"],
error,
code(cxt) {
const { gen, schema, data, it } = cxt;
const items = it.items || 0;
if (items === true)
return;
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
if (schema === false) {
cxt.setParams({ len: items });
cxt.fail((0, codegen_1._)`${len} > ${items}`);
} else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`);
gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
cxt.ok(valid);
}
it.items = true;
function validateItems(valid, from) {
gen.forRange("i", from, len, (i) => {
cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid);
if (!it.allErrors)
gen.if((0, codegen_1.not)(valid), () => gen.break());
});
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/unevaluated/index.js
var require_unevaluated = __commonJS({
"node_modules/ajv/dist/vocabularies/unevaluated/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var unevaluatedProperties_1 = require_unevaluatedProperties();
var unevaluatedItems_1 = require_unevaluatedItems();
var unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
exports.default = unevaluated;
}
});
// node_modules/ajv/dist/vocabularies/format/format.js
var require_format = __commonJS({
"node_modules/ajv/dist/vocabularies/format/format.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var error = {
message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
};
var def = {
keyword: "format",
type: ["number", "string"],
schemaType: "string",
$data: true,
error,
code(cxt, ruleType) {
const { gen, data, $data, schema, schemaCode, it } = cxt;
const { opts, errSchemaPath, schemaEnv, self } = it;
if (!opts.validateFormats)
return;
if ($data)
validate$DataFormat();
else
validateFormat();
function validate$DataFormat() {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats
});
const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
const fType = gen.let("fType");
const format = gen.let("format");
gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
function unknownFmt() {
if (opts.strictSchema === false)
return codegen_1.nil;
return (0, codegen_1._)`${schemaCode} && !${format}`;
}
function invalidFmt() {
const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
}
}
function validateFormat() {
const formatDef = self.formats[schema];
if (!formatDef) {
unknownFormat();
return;
}
if (formatDef === true)
return;
const [fmtType, format, fmtRef] = getFormat(formatDef);
if (fmtType === ruleType)
cxt.pass(validCondition());
function unknownFormat() {
if (opts.strictSchema === false) {
self.logger.warn(unknownMsg());
return;
}
throw new Error(unknownMsg());
function unknownMsg() {
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
}
}
function getFormat(fmtDef) {
const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
}
return ["string", fmtDef, fmt];
}
function validCondition() {
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
if (!schemaEnv.$async)
throw new Error("async format in sync schema");
return (0, codegen_1._)`await ${fmtRef}(${data})`;
}
return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
}
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/vocabularies/format/index.js
var require_format2 = __commonJS({
"node_modules/ajv/dist/vocabularies/format/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var format_1 = require_format();
var format = [format_1.default];
exports.default = format;
}
});
// node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata = __commonJS({
"node_modules/ajv/dist/vocabularies/metadata.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
"title",
"description",
"default",
"deprecated",
"readOnly",
"writeOnly",
"examples"
];
exports.contentVocabulary = [
"contentMediaType",
"contentEncoding",
"contentSchema"
];
}
});
// node_modules/ajv/dist/vocabularies/draft2020.js
var require_draft2020 = __commonJS({
"node_modules/ajv/dist/vocabularies/draft2020.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require_core2();
var validation_1 = require_validation();
var applicator_1 = require_applicator();
var dynamic_1 = require_dynamic();
var next_1 = require_next();
var unevaluated_1 = require_unevaluated();
var format_1 = require_format2();
var metadata_1 = require_metadata();
var draft2020Vocabularies = [
dynamic_1.default,
core_1.default,
validation_1.default,
(0, applicator_1.default)(true),
format_1.default,
metadata_1.metadataVocabulary,
metadata_1.contentVocabulary,
next_1.default,
unevaluated_1.default
];
exports.default = draft2020Vocabularies;
}
});
// node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types = __commonJS({
"node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiscrError = void 0;
var DiscrError;
(function(DiscrError2) {
DiscrError2["Tag"] = "tag";
DiscrError2["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
}
});
// node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator = __commonJS({
"node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var codegen_1 = require_codegen();
var types_1 = require_types();
var compile_1 = require_compile();
var ref_error_1 = require_ref_error();
var util_1 = require_util();
var error = {
message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
};
var def = {
keyword: "discriminator",
type: "object",
schemaType: "object",
error,
code(cxt) {
const { gen, data, schema, parentSchema, it } = cxt;
const { oneOf: oneOf2 } = parentSchema;
if (!it.opts.discriminator) {
throw new Error("discriminator: requires discriminator option");
}
const tagName = schema.propertyName;
if (typeof tagName != "string")
throw new Error("discriminator: requires propertyName");
if (schema.mapping)
throw new Error("discriminator: mapping is not supported");
if (!oneOf2)
throw new Error("discriminator: requires oneOf keyword");
const valid = gen.let("valid", false);
const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
cxt.ok(valid);
function validateMapping() {
const mapping = getMapping();
gen.if(false);
for (const tagValue in mapping) {
gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
gen.assign(valid, applyTagSchema(mapping[tagValue]));
}
gen.else();
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
gen.endIf();
}
function applyTagSchema(schemaProp) {
const _valid = gen.name("valid");
const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
cxt.mergeEvaluated(schCxt, codegen_1.Name);
return _valid;
}
function getMapping() {
var _a;
const oneOfMapping = {};
const topRequired = hasRequired(parentSchema);
let tagRequired = true;
for (let i = 0; i < oneOf2.length; i++) {
let sch = oneOf2[i];
if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
const ref = sch.$ref;
sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
if (sch instanceof compile_1.SchemaEnv)
sch = sch.schema;
if (sch === void 0)
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
}
const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
if (typeof propSch != "object") {
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
}
tagRequired = tagRequired && (topRequired || hasRequired(sch));
addMappings(propSch, i);
}
if (!tagRequired)
throw new Error(`discriminator: "${tagName}" must be required`);
return oneOfMapping;
function hasRequired({ required: required2 }) {
return Array.isArray(required2) && required2.includes(tagName);
}
function addMappings(sch, i) {
if (sch.const) {
addMapping(sch.const, i);
} else if (sch.enum) {
for (const tagValue of sch.enum) {
addMapping(tagValue, i);
}
} else {
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
}
}
function addMapping(tagValue, i) {
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
}
oneOfMapping[tagValue] = i;
}
}
}
};
exports.default = def;
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/schema.json
var require_schema = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/schema.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/schema",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/core": true,
"https://json-schema.org/draft/2020-12/vocab/applicator": true,
"https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
"https://json-schema.org/draft/2020-12/vocab/validation": true,
"https://json-schema.org/draft/2020-12/vocab/meta-data": true,
"https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
"https://json-schema.org/draft/2020-12/vocab/content": true
},
$dynamicAnchor: "meta",
title: "Core and Validation specifications meta-schema",
allOf: [
{ $ref: "meta/core" },
{ $ref: "meta/applicator" },
{ $ref: "meta/unevaluated" },
{ $ref: "meta/validation" },
{ $ref: "meta/meta-data" },
{ $ref: "meta/format-annotation" },
{ $ref: "meta/content" }
],
type: ["object", "boolean"],
$comment: "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
properties: {
definitions: {
$comment: '"definitions" has been replaced by "$defs".',
type: "object",
additionalProperties: { $dynamicRef: "#meta" },
deprecated: true,
default: {}
},
dependencies: {
$comment: '"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',
type: "object",
additionalProperties: {
anyOf: [{ $dynamicRef: "#meta" }, { $ref: "meta/validation#/$defs/stringArray" }]
},
deprecated: true,
default: {}
},
$recursiveAnchor: {
$comment: '"$recursiveAnchor" has been replaced by "$dynamicAnchor".',
$ref: "meta/core#/$defs/anchorString",
deprecated: true
},
$recursiveRef: {
$comment: '"$recursiveRef" has been replaced by "$dynamicRef".',
$ref: "meta/core#/$defs/uriReferenceString",
deprecated: true
}
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json
var require_applicator2 = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/applicator",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/applicator": true
},
$dynamicAnchor: "meta",
title: "Applicator vocabulary meta-schema",
type: ["object", "boolean"],
properties: {
prefixItems: { $ref: "#/$defs/schemaArray" },
items: { $dynamicRef: "#meta" },
contains: { $dynamicRef: "#meta" },
additionalProperties: { $dynamicRef: "#meta" },
properties: {
type: "object",
additionalProperties: { $dynamicRef: "#meta" },
default: {}
},
patternProperties: {
type: "object",
additionalProperties: { $dynamicRef: "#meta" },
propertyNames: { format: "regex" },
default: {}
},
dependentSchemas: {
type: "object",
additionalProperties: { $dynamicRef: "#meta" },
default: {}
},
propertyNames: { $dynamicRef: "#meta" },
if: { $dynamicRef: "#meta" },
then: { $dynamicRef: "#meta" },
else: { $dynamicRef: "#meta" },
allOf: { $ref: "#/$defs/schemaArray" },
anyOf: { $ref: "#/$defs/schemaArray" },
oneOf: { $ref: "#/$defs/schemaArray" },
not: { $dynamicRef: "#meta" }
},
$defs: {
schemaArray: {
type: "array",
minItems: 1,
items: { $dynamicRef: "#meta" }
}
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json
var require_unevaluated2 = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/unevaluated",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/unevaluated": true
},
$dynamicAnchor: "meta",
title: "Unevaluated applicator vocabulary meta-schema",
type: ["object", "boolean"],
properties: {
unevaluatedItems: { $dynamicRef: "#meta" },
unevaluatedProperties: { $dynamicRef: "#meta" }
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json
var require_content = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/content",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/content": true
},
$dynamicAnchor: "meta",
title: "Content vocabulary meta-schema",
type: ["object", "boolean"],
properties: {
contentEncoding: { type: "string" },
contentMediaType: { type: "string" },
contentSchema: { $dynamicRef: "#meta" }
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json
var require_core3 = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/core",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/core": true
},
$dynamicAnchor: "meta",
title: "Core vocabulary meta-schema",
type: ["object", "boolean"],
properties: {
$id: {
$ref: "#/$defs/uriReferenceString",
$comment: "Non-empty fragments not allowed.",
pattern: "^[^#]*#?$"
},
$schema: { $ref: "#/$defs/uriString" },
$ref: { $ref: "#/$defs/uriReferenceString" },
$anchor: { $ref: "#/$defs/anchorString" },
$dynamicRef: { $ref: "#/$defs/uriReferenceString" },
$dynamicAnchor: { $ref: "#/$defs/anchorString" },
$vocabulary: {
type: "object",
propertyNames: { $ref: "#/$defs/uriString" },
additionalProperties: {
type: "boolean"
}
},
$comment: {
type: "string"
},
$defs: {
type: "object",
additionalProperties: { $dynamicRef: "#meta" }
}
},
$defs: {
anchorString: {
type: "string",
pattern: "^[A-Za-z_][-A-Za-z0-9._]*$"
},
uriString: {
type: "string",
format: "uri"
},
uriReferenceString: {
type: "string",
format: "uri-reference"
}
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json
var require_format_annotation = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/format-annotation",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/format-annotation": true
},
$dynamicAnchor: "meta",
title: "Format vocabulary meta-schema for annotation results",
type: ["object", "boolean"],
properties: {
format: { type: "string" }
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json
var require_meta_data = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/meta-data",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/meta-data": true
},
$dynamicAnchor: "meta",
title: "Meta-data vocabulary meta-schema",
type: ["object", "boolean"],
properties: {
title: {
type: "string"
},
description: {
type: "string"
},
default: true,
deprecated: {
type: "boolean",
default: false
},
readOnly: {
type: "boolean",
default: false
},
writeOnly: {
type: "boolean",
default: false
},
examples: {
type: "array",
items: true
}
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json
var require_validation2 = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json"(exports, module) {
module.exports = {
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: "https://json-schema.org/draft/2020-12/meta/validation",
$vocabulary: {
"https://json-schema.org/draft/2020-12/vocab/validation": true
},
$dynamicAnchor: "meta",
title: "Validation vocabulary meta-schema",
type: ["object", "boolean"],
properties: {
type: {
anyOf: [
{ $ref: "#/$defs/simpleTypes" },
{
type: "array",
items: { $ref: "#/$defs/simpleTypes" },
minItems: 1,
uniqueItems: true
}
]
},
const: true,
enum: {
type: "array",
items: true
},
multipleOf: {
type: "number",
exclusiveMinimum: 0
},
maximum: {
type: "number"
},
exclusiveMaximum: {
type: "number"
},
minimum: {
type: "number"
},
exclusiveMinimum: {
type: "number"
},
maxLength: { $ref: "#/$defs/nonNegativeInteger" },
minLength: { $ref: "#/$defs/nonNegativeIntegerDefault0" },
pattern: {
type: "string",
format: "regex"
},
maxItems: { $ref: "#/$defs/nonNegativeInteger" },
minItems: { $ref: "#/$defs/nonNegativeIntegerDefault0" },
uniqueItems: {
type: "boolean",
default: false
},
maxContains: { $ref: "#/$defs/nonNegativeInteger" },
minContains: {
$ref: "#/$defs/nonNegativeInteger",
default: 1
},
maxProperties: { $ref: "#/$defs/nonNegativeInteger" },
minProperties: { $ref: "#/$defs/nonNegativeIntegerDefault0" },
required: { $ref: "#/$defs/stringArray" },
dependentRequired: {
type: "object",
additionalProperties: {
$ref: "#/$defs/stringArray"
}
}
},
$defs: {
nonNegativeInteger: {
type: "integer",
minimum: 0
},
nonNegativeIntegerDefault0: {
$ref: "#/$defs/nonNegativeInteger",
default: 0
},
simpleTypes: {
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
},
stringArray: {
type: "array",
items: { type: "string" },
uniqueItems: true,
default: []
}
}
};
}
});
// node_modules/ajv/dist/refs/json-schema-2020-12/index.js
var require_json_schema_2020_12 = __commonJS({
"node_modules/ajv/dist/refs/json-schema-2020-12/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var metaSchema = require_schema();
var applicator = require_applicator2();
var unevaluated = require_unevaluated2();
var content = require_content();
var core = require_core3();
var format = require_format_annotation();
var metadata = require_meta_data();
var validation = require_validation2();
var META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2020($data) {
;
[
metaSchema,
applicator,
unevaluated,
content,
core,
with$data(this, format),
metadata,
with$data(this, validation)
].forEach((sch) => this.addMetaSchema(sch, void 0, false));
return this;
function with$data(ajv, sch) {
return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
}
}
exports.default = addMetaSchema2020;
}
});
// node_modules/ajv/dist/2020.js
var require__ = __commonJS({
"node_modules/ajv/dist/2020.js"(exports, module) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0;
var core_1 = require_core();
var draft2020_1 = require_draft2020();
var discriminator_1 = require_discriminator();
var json_schema_2020_12_1 = require_json_schema_2020_12();
var META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
var Ajv20202 = class extends core_1.default {
constructor(opts = {}) {
super({
...opts,
dynamicRef: true,
next: true,
unevaluated: true
});
}
_addVocabularies() {
super._addVocabularies();
draft2020_1.default.forEach((v) => this.addVocabulary(v));
if (this.opts.discriminator)
this.addKeyword(discriminator_1.default);
}
_addDefaultMetaSchema() {
super._addDefaultMetaSchema();
const { $data, meta } = this.opts;
if (!meta)
return;
json_schema_2020_12_1.default.call(this, $data);
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
}
defaultMeta() {
return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
}
};
exports.Ajv2020 = Ajv20202;
module.exports = exports = Ajv20202;
module.exports.Ajv2020 = Ajv20202;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv20202;
var validate_1 = require_validate();
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
return validate_1.KeywordCxt;
} });
var codegen_1 = require_codegen();
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
return codegen_1._;
} });
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
return codegen_1.str;
} });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
return codegen_1.stringify;
} });
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
return codegen_1.nil;
} });
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
return codegen_1.Name;
} });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
return codegen_1.CodeGen;
} });
var validation_error_1 = require_validation_error();
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
return validation_error_1.default;
} });
var ref_error_1 = require_ref_error();
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
return ref_error_1.default;
} });
}
});
// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS({
"node_modules/yaml/dist/nodes/identity.js"(exports) {
"use strict";
var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias");
var DOC = /* @__PURE__ */ Symbol.for("yaml.document");
var MAP = /* @__PURE__ */ Symbol.for("yaml.map");
var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair");
var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar");
var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq");
var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
var isAlias2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
var isMap2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
var isScalar2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
function isCollection2(node) {
if (node && typeof node === "object")
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === "object")
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
var hasAnchor = (node) => (isScalar2(node) || isCollection2(node)) && !!node.anchor;
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias2;
exports.isCollection = isCollection2;
exports.isDocument = isDocument;
exports.isMap = isMap2;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar2;
exports.isSeq = isSeq;
}
});
// node_modules/yaml/dist/visit.js
var require_visit = __commonJS({
"node_modules/yaml/dist/visit.js"(exports) {
"use strict";
var identity = require_identity();
var BREAK = /* @__PURE__ */ Symbol("break visit");
var SKIP = /* @__PURE__ */ Symbol("skip children");
var REMOVE = /* @__PURE__ */ Symbol("remove node");
function visit2(node, visitor) {
const visitor_ = initVisitor(visitor);
if (identity.isDocument(node)) {
const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
} else
visit_(null, node, visitor_, Object.freeze([]));
}
visit2.BREAK = BREAK;
visit2.SKIP = SKIP;
visit2.REMOVE = REMOVE;
function visit_(key, node, visitor, path) {
const ctrl = callVisitor(key, node, visitor, path);
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visit_(key, ctrl, visitor, path);
}
if (typeof ctrl !== "symbol") {
if (identity.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = visit_(i, node.items[i], visitor, path);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i, 1);
i -= 1;
}
}
} else if (identity.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = visit_("key", node.key, visitor, path);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = visit_("value", node.value, visitor, path);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
async function visitAsync(node, visitor) {
const visitor_ = initVisitor(visitor);
if (identity.isDocument(node)) {
const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
} else
await visitAsync_(null, node, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK;
visitAsync.SKIP = SKIP;
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key, node, visitor, path) {
const ctrl = await callVisitor(key, node, visitor, path);
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visitAsync_(key, ctrl, visitor, path);
}
if (typeof ctrl !== "symbol") {
if (identity.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = await visitAsync_(i, node.items[i], visitor, path);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i, 1);
i -= 1;
}
}
} else if (identity.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = await visitAsync_("key", node.key, visitor, path);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = await visitAsync_("value", node.value, visitor, path);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
function initVisitor(visitor) {
if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
return Object.assign({
Alias: visitor.Node,
Map: visitor.Node,
Scalar: visitor.Node,
Seq: visitor.Node
}, visitor.Value && {
Map: visitor.Value,
Scalar: visitor.Value,
Seq: visitor.Value
}, visitor.Collection && {
Map: visitor.Collection,
Seq: visitor.Collection
}, visitor);
}
return visitor;
}
function callVisitor(key, node, visitor, path) {
if (typeof visitor === "function")
return visitor(key, node, path);
if (identity.isMap(node))
return visitor.Map?.(key, node, path);
if (identity.isSeq(node))
return visitor.Seq?.(key, node, path);
if (identity.isPair(node))
return visitor.Pair?.(key, node, path);
if (identity.isScalar(node))
return visitor.Scalar?.(key, node, path);
if (identity.isAlias(node))
return visitor.Alias?.(key, node, path);
return void 0;
}
function replaceNode(key, path, node) {
const parent = path[path.length - 1];
if (identity.isCollection(parent)) {
parent.items[key] = node;
} else if (identity.isPair(parent)) {
if (key === "key")
parent.key = node;
else
parent.value = node;
} else if (identity.isDocument(parent)) {
parent.contents = node;
} else {
const pt = identity.isAlias(parent) ? "alias" : "scalar";
throw new Error(`Cannot replace node with ${pt} parent`);
}
}
exports.visit = visit2;
exports.visitAsync = visitAsync;
}
});
// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS({
"node_modules/yaml/dist/doc/directives.js"(exports) {
"use strict";
var identity = require_identity();
var visit2 = require_visit();
var escapeChars = {
"!": "%21",
",": "%2C",
"[": "%5B",
"]": "%5D",
"{": "%7B",
"}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
var Directives = class _Directives {
constructor(yaml, tags) {
this.docStart = null;
this.docEnd = false;
this.yaml = Object.assign({}, _Directives.defaultYaml, yaml);
this.tags = Object.assign({}, _Directives.defaultTags, tags);
}
clone() {
const copy = new _Directives(this.yaml, this.tags);
copy.docStart = this.docStart;
return copy;
}
/**
* During parsing, get a Directives instance for the current document and
* update the stream state according to the current version's spec.
*/
atDocument() {
const res = new _Directives(this.yaml, this.tags);
switch (this.yaml.version) {
case "1.1":
this.atNextDocument = true;
break;
case "1.2":
this.atNextDocument = false;
this.yaml = {
explicit: _Directives.defaultYaml.explicit,
version: "1.2"
};
this.tags = Object.assign({}, _Directives.defaultTags);
break;
}
return res;
}
/**
* @param onError - May be called even if the action was successful
* @returns `true` on success
*/
add(line, onError) {
if (this.atNextDocument) {
this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
this.tags = Object.assign({}, _Directives.defaultTags);
this.atNextDocument = false;
}
const parts = line.trim().split(/[ \t]+/);
const name = parts.shift();
switch (name) {
case "%TAG": {
if (parts.length !== 2) {
onError(0, "%TAG directive should contain exactly two parts");
if (parts.length < 2)
return false;
}
const [handle, prefix] = parts;
this.tags[handle] = prefix;
return true;
}
case "%YAML": {
this.yaml.explicit = true;
if (parts.length !== 1) {
onError(0, "%YAML directive should contain exactly one part");
return false;
}
const [version] = parts;
if (version === "1.1" || version === "1.2") {
this.yaml.version = version;
return true;
} else {
const isValid = /^\d+\.\d+$/.test(version);
onError(6, `Unsupported YAML version ${version}`, isValid);
return false;
}
}
default:
onError(0, `Unknown directive ${name}`, true);
return false;
}
}
/**
* Resolves a tag, matching handles to those defined in %TAG directives.
*
* @returns Resolved tag, which may also be the non-specific tag `'!'` or a
* `'!local'` tag, or `null` if unresolvable.
*/
tagName(source, onError) {
if (source === "!")
return "!";
if (source[0] !== "!") {
onError(`Not a valid tag: ${source}`);
return null;
}
if (source[1] === "<") {
const verbatim = source.slice(2, -1);
if (verbatim === "!" || verbatim === "!!") {
onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
return null;
}
if (source[source.length - 1] !== ">")
onError("Verbatim tags must end with a >");
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
} catch (error) {
onError(String(error));
return null;
}
}
if (handle === "!")
return source;
onError(`Could not resolve tag: ${source}`);
return null;
}
/**
* Given a fully resolved tag, returns its printable string form,
* taking into account current tag prefixes and defaults.
*/
tagString(tag) {
for (const [handle, prefix] of Object.entries(this.tags)) {
if (tag.startsWith(prefix))
return handle + escapeTagName(tag.substring(prefix.length));
}
return tag[0] === "!" ? tag : `!<${tag}>`;
}
toString(doc) {
const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
const tags = {};
visit2.visit(doc.contents, (_key, node) => {
if (identity.isNode(node) && node.tag)
tags[node.tag] = true;
});
tagNames = Object.keys(tags);
} else
tagNames = [];
for (const [handle, prefix] of tagEntries) {
if (handle === "!!" && prefix === "tag:yaml.org,2002:")
continue;
if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
lines.push(`%TAG ${handle} ${prefix}`);
}
return lines.join("\n");
}
};
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
exports.Directives = Directives;
}
});
// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS({
"node_modules/yaml/dist/doc/anchors.js"(exports) {
"use strict";
var identity = require_identity();
var visit2 = require_visit();
function anchorIsValid(anchor) {
if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
const sa = JSON.stringify(anchor);
const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
throw new Error(msg);
}
return true;
}
function anchorNames(root) {
const anchors = /* @__PURE__ */ new Set();
visit2.visit(root, {
Value(_key, node) {
if (node.anchor)
anchors.add(node.anchor);
}
});
return anchors;
}
function findNewAnchor(prefix, exclude) {
for (let i = 1; true; ++i) {
const name = `${prefix}${i}`;
if (!exclude.has(name))
return name;
}
}
function createNodeAnchors(doc, prefix) {
const aliasObjects = [];
const sourceObjects = /* @__PURE__ */ new Map();
let prevAnchors = null;
return {
onAnchor: (source) => {
aliasObjects.push(source);
prevAnchors ?? (prevAnchors = anchorNames(doc));
const anchor = findNewAnchor(prefix, prevAnchors);
prevAnchors.add(anchor);
return anchor;
},
/**
* With circular references, the source node is only resolved after all
* of its child nodes are. This is why anchors are set only after all of
* the nodes have been created.
*/
setAnchors: () => {
for (const source of aliasObjects) {
const ref = sourceObjects.get(source);
if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
ref.node.anchor = ref.anchor;
} else {
const error = new Error("Failed to resolve repeated object (this should not happen)");
error.source = source;
throw error;
}
}
},
sourceObjects
};
}
exports.anchorIsValid = anchorIsValid;
exports.anchorNames = anchorNames;
exports.createNodeAnchors = createNodeAnchors;
exports.findNewAnchor = findNewAnchor;
}
});
// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS({
"node_modules/yaml/dist/doc/applyReviver.js"(exports) {
"use strict";
function applyReviver(reviver, obj, key, val) {
if (val && typeof val === "object") {
if (Array.isArray(val)) {
for (let i = 0, len = val.length; i < len; ++i) {
const v0 = val[i];
const v1 = applyReviver(reviver, val, String(i), v0);
if (v1 === void 0)
delete val[i];
else if (v1 !== v0)
val[i] = v1;
}
} else if (val instanceof Map) {
for (const k of Array.from(val.keys())) {
const v0 = val.get(k);
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === void 0)
val.delete(k);
else if (v1 !== v0)
val.set(k, v1);
}
} else if (val instanceof Set) {
for (const v0 of Array.from(val)) {
const v1 = applyReviver(reviver, val, v0, v0);
if (v1 === void 0)
val.delete(v0);
else if (v1 !== v0) {
val.delete(v0);
val.add(v1);
}
}
} else {
for (const [k, v0] of Object.entries(val)) {
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === void 0)
delete val[k];
else if (v1 !== v0)
val[k] = v1;
}
}
}
return reviver.call(obj, key, val);
}
exports.applyReviver = applyReviver;
}
});
// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS({
"node_modules/yaml/dist/nodes/toJS.js"(exports) {
"use strict";
var identity = require_identity();
function toJS(value, arg, ctx) {
if (Array.isArray(value))
return value.map((v, i) => toJS(v, String(i), ctx));
if (value && typeof value.toJSON === "function") {
if (!ctx || !identity.hasAnchor(value))
return value.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: void 0 };
ctx.anchors.set(value, data);
ctx.onCreate = (res2) => {
data.res = res2;
delete ctx.onCreate;
};
const res = value.toJSON(arg, ctx);
if (ctx.onCreate)
ctx.onCreate(res);
return res;
}
if (typeof value === "bigint" && !ctx?.keep)
return Number(value);
return value;
}
exports.toJS = toJS;
}
});
// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS({
"node_modules/yaml/dist/nodes/Node.js"(exports) {
"use strict";
var applyReviver = require_applyReviver();
var identity = require_identity();
var toJS = require_toJS();
var NodeBase = class {
constructor(type) {
Object.defineProperty(this, identity.NODE_TYPE, { value: type });
}
/** Create a copy of this node. */
clone() {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** A plain JavaScript representation of this node. */
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!identity.isDocument(doc))
throw new TypeError("A document argument is required");
const ctx = {
anchors: /* @__PURE__ */ new Map(),
doc,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS.toJS(this, "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
}
};
exports.NodeBase = NodeBase;
}
});
// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS({
"node_modules/yaml/dist/nodes/Alias.js"(exports) {
"use strict";
var anchors = require_anchors();
var visit2 = require_visit();
var identity = require_identity();
var Node = require_Node();
var toJS = require_toJS();
var Alias = class extends Node.NodeBase {
constructor(source) {
super(identity.ALIAS);
this.source = source;
Object.defineProperty(this, "tag", {
set() {
throw new Error("Alias nodes cannot have tags");
}
});
}
/**
* Resolve the value of this alias within `doc`, finding the last
* instance of the `source` anchor before this node.
*/
resolve(doc, ctx) {
if (ctx?.maxAliasCount === 0)
throw new ReferenceError("Alias resolution is disabled");
let nodes;
if (ctx?.aliasResolveCache) {
nodes = ctx.aliasResolveCache;
} else {
nodes = [];
visit2.visit(doc, {
Node: (_key, node) => {
if (identity.isAlias(node) || identity.hasAnchor(node))
nodes.push(node);
}
});
if (ctx)
ctx.aliasResolveCache = nodes;
}
let found = void 0;
for (const node of nodes) {
if (node === this)
break;
if (node.anchor === this.source)
found = node;
}
if (found && ctx) {
const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx;
let data = anchors2.get(found);
if (!data) {
toJS.toJS(found, null, ctx);
data = anchors2.get(found);
}
if (data?.res === void 0) {
const msg = "This should not happen: Alias anchor was not resolved?";
throw new ReferenceError(msg);
}
if (maxAliasCount >= 0) {
data.count += 1;
if (data.aliasCount === 0)
data.aliasCount = getAliasCount(doc2, found, anchors2);
if (data.count * data.aliasCount > maxAliasCount) {
const msg = "Excessive alias count indicates a resource exhaustion attack";
throw new ReferenceError(msg);
}
}
}
return found;
}
toJSON(_arg, ctx) {
if (!ctx)
return { source: this.source };
const source = this.resolve(ctx.doc, ctx);
if (!source) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
return ctx.anchors.get(source).res;
}
toString(ctx, _onComment, _onChompKeep) {
const src = `*${this.source}`;
if (ctx) {
anchors.anchorIsValid(this.source);
if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new Error(msg);
}
if (ctx.implicitKey)
return `${src} `;
}
return src;
}
};
function getAliasCount(doc, node, anchors2) {
if (identity.isAlias(node)) {
const source = node.resolve(doc);
const anchor = anchors2 && source && anchors2.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
} else if (identity.isCollection(node)) {
let count = 0;
for (const item of node.items) {
const c = getAliasCount(doc, item, anchors2);
if (c > count)
count = c;
}
return count;
} else if (identity.isPair(node)) {
const kc = getAliasCount(doc, node.key, anchors2);
const vc = getAliasCount(doc, node.value, anchors2);
return Math.max(kc, vc);
}
return 1;
}
exports.Alias = Alias;
}
});
// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS({
"node_modules/yaml/dist/nodes/Scalar.js"(exports) {
"use strict";
var identity = require_identity();
var Node = require_Node();
var toJS = require_toJS();
var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
var Scalar = class extends Node.NodeBase {
constructor(value) {
super(identity.SCALAR);
this.value = value;
}
toJSON(arg, ctx) {
return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
}
toString() {
return String(this.value);
}
};
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
exports.Scalar = Scalar;
exports.isScalarValue = isScalarValue;
}
});
// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS({
"node_modules/yaml/dist/doc/createNode.js"(exports) {
"use strict";
var Alias = require_Alias();
var identity = require_identity();
var Scalar = require_Scalar();
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value, tagName, tags) {
if (tagName) {
const match = tags.filter((t) => t.tag === tagName);
const tagObj = match.find((t) => !t.format) ?? match[0];
if (!tagObj)
throw new Error(`Tag ${tagName} not found`);
return tagObj;
}
return tags.find((t) => t.identify?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
if (identity.isDocument(value))
value = value.contents;
if (identity.isNode(value))
return value;
if (identity.isPair(value)) {
const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
map.items.push(value);
return map;
}
if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
value = value.valueOf();
}
const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
let ref = void 0;
if (aliasDuplicateObjects && value && typeof value === "object") {
ref = sourceObjects.get(value);
if (ref) {
ref.anchor ?? (ref.anchor = onAnchor(value));
return new Alias.Alias(ref.anchor);
} else {
ref = { anchor: null, node: null };
sourceObjects.set(value, ref);
}
}
if (tagName?.startsWith("!!"))
tagName = defaultTagPrefix + tagName.slice(2);
let tagObj = findTagObject(value, tagName, schema.tags);
if (!tagObj) {
if (value && typeof value.toJSON === "function") {
value = value.toJSON();
}
if (!value || typeof value !== "object") {
const node2 = new Scalar.Scalar(value);
if (ref)
ref.node = node2;
return node2;
}
tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP];
}
if (onTagObj) {
onTagObj(tagObj);
delete ctx.onTagObj;
}
const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;
}
exports.createNode = createNode;
}
});
// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS({
"node_modules/yaml/dist/nodes/Collection.js"(exports) {
"use strict";
var createNode = require_createNode();
var identity = require_identity();
var Node = require_Node();
function collectionFromPath(schema, path, value) {
let v = value;
for (let i = path.length - 1; i >= 0; --i) {
const k = path[i];
if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
const a = [];
a[k] = v;
v = a;
} else {
v = /* @__PURE__ */ new Map([[k, v]]);
}
}
return createNode.createNode(v, void 0, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error("This should not happen, please report a bug.");
},
schema,
sourceObjects: /* @__PURE__ */ new Map()
});
}
var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
var Collection = class extends Node.NodeBase {
constructor(type, schema) {
super(type);
Object.defineProperty(this, "schema", {
value: schema,
configurable: true,
enumerable: false,
writable: true
});
}
/**
* Create a copy of this collection.
*
* @param schema - If defined, overwrites the original's schema
*/
clone(schema) {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema)
copy.schema = schema;
copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
}
/**
* Adds a value to the collection. For `!!map` and `!!omap` the value must
* be a Pair instance or a `{ key, value }` object, which may not have a key
* that already exists in the map.
*/
addIn(path, value) {
if (isEmptyPath(path))
this.add(value);
else {
const [key, ...rest] = path;
const node = this.get(key, true);
if (identity.isCollection(node))
node.addIn(rest, value);
else if (node === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
/**
* Removes a value from the collection.
* @returns `true` if the item was found and removed.
*/
deleteIn(path) {
const [key, ...rest] = path;
if (rest.length === 0)
return this.delete(key);
const node = this.get(key, true);
if (identity.isCollection(node))
return node.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path, keepScalar) {
const [key, ...rest] = path;
const node = this.get(key, true);
if (rest.length === 0)
return !keepScalar && identity.isScalar(node) ? node.value : node;
else
return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
}
hasAllNullValues(allowScalar) {
return this.items.every((node) => {
if (!identity.isPair(node))
return false;
const n = node.value;
return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
});
}
/**
* Checks if the collection includes a value with the key `key`.
*/
hasIn(path) {
const [key, ...rest] = path;
if (rest.length === 0)
return this.has(key);
const node = this.get(key, true);
return identity.isCollection(node) ? node.hasIn(rest) : false;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
const [key, ...rest] = path;
if (rest.length === 0) {
this.set(key, value);
} else {
const node = this.get(key, true);
if (identity.isCollection(node))
node.setIn(rest, value);
else if (node === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
};
exports.Collection = Collection;
exports.collectionFromPath = collectionFromPath;
exports.isEmptyPath = isEmptyPath;
}
});
// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS({
"node_modules/yaml/dist/stringify/stringifyComment.js"(exports) {
"use strict";
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment, indent) {
if (/^\n+$/.test(comment))
return comment.substring(1);
return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
exports.indentComment = indentComment;
exports.lineComment = lineComment;
exports.stringifyComment = stringifyComment;
}
});
// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS({
"node_modules/yaml/dist/stringify/foldFlowLines.js"(exports) {
"use strict";
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
if (!lineWidth || lineWidth < 0)
return text;
if (lineWidth < minContentWidth)
minContentWidth = 0;
const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
if (text.length <= endStep)
return text;
const folds = [];
const escapedFolds = {};
let end = lineWidth - indent.length;
if (typeof indentAtStart === "number") {
if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
folds.push(0);
else
end = lineWidth - indentAtStart;
}
let split = void 0;
let prev = void 0;
let overflow = false;
let i = -1;
let escStart = -1;
let escEnd = -1;
if (mode === FOLD_BLOCK) {
i = consumeMoreIndentedLines(text, i, indent.length);
if (i !== -1)
end = i + endStep;
}
for (let ch; ch = text[i += 1]; ) {
if (mode === FOLD_QUOTED && ch === "\\") {
escStart = i;
switch (text[i + 1]) {
case "x":
i += 3;
break;
case "u":
i += 5;
break;
case "U":
i += 9;
break;
default:
i += 1;
}
escEnd = i;
}
if (ch === "\n") {
if (mode === FOLD_BLOCK)
i = consumeMoreIndentedLines(text, i, indent.length);
end = i + indent.length + endStep;
split = void 0;
} else {
if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") {
const next = text[i + 1];
if (next && next !== " " && next !== "\n" && next !== " ")
split = i;
}
if (i >= end) {
if (split) {
folds.push(split);
end = split + endStep;
split = void 0;
} else if (mode === FOLD_QUOTED) {
while (prev === " " || prev === " ") {
prev = ch;
ch = text[i += 1];
overflow = true;
}
const j = i > escEnd + 1 ? i - 2 : escStart - 1;
if (escapedFolds[j])
return text;
folds.push(j);
escapedFolds[j] = true;
end = j + endStep;
split = void 0;
} else {
overflow = true;
}
}
}
prev = ch;
}
if (overflow && onOverflow)
onOverflow();
if (folds.length === 0)
return text;
if (onFold)
onFold();
let res = text.slice(0, folds[0]);
for (let i2 = 0; i2 < folds.length; ++i2) {
const fold = folds[i2];
const end2 = folds[i2 + 1] || text.length;
if (fold === 0)
res = `
${indent}${text.slice(0, end2)}`;
else {
if (mode === FOLD_QUOTED && escapedFolds[fold])
res += `${text[fold]}\\`;
res += `
${indent}${text.slice(fold + 1, end2)}`;
}
}
return res;
}
function consumeMoreIndentedLines(text, i, indent) {
let end = i;
let start = i + 1;
let ch = text[start];
while (ch === " " || ch === " ") {
if (i < start + indent) {
ch = text[++i];
} else {
do {
ch = text[++i];
} while (ch && ch !== "\n");
end = i;
start = i + 1;
ch = text[start];
}
}
return end;
}
exports.FOLD_BLOCK = FOLD_BLOCK;
exports.FOLD_FLOW = FOLD_FLOW;
exports.FOLD_QUOTED = FOLD_QUOTED;
exports.foldFlowLines = foldFlowLines;
}
});
// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS({
"node_modules/yaml/dist/stringify/stringifyString.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var foldFlowLines = require_foldFlowLines();
var getFoldOptions = (ctx, isBlock) => ({
indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
if (!lineWidth || lineWidth < 0)
return false;
const limit = lineWidth - indentLength;
const strLen = str.length;
if (strLen <= limit)
return false;
for (let i = 0, start = 0; i < strLen; ++i) {
if (str[i] === "\n") {
if (i - start > limit)
return true;
start = i + 1;
if (strLen - start <= limit)
return false;
}
}
return true;
}
function doubleQuotedString(value, ctx) {
const json = JSON.stringify(value);
if (ctx.options.doubleQuotedAsJSON)
return json;
const { implicitKey } = ctx;
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
let str = "";
let start = 0;
for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
str += json.slice(start, i) + "\\ ";
i += 1;
start = i;
ch = "\\";
}
if (ch === "\\")
switch (json[i + 1]) {
case "u":
{
str += json.slice(start, i);
const code = json.substr(i + 2, 4);
switch (code) {
case "0000":
str += "\\0";
break;
case "0007":
str += "\\a";
break;
case "000b":
str += "\\v";
break;
case "001b":
str += "\\e";
break;
case "0085":
str += "\\N";
break;
case "00a0":
str += "\\_";
break;
case "2028":
str += "\\L";
break;
case "2029":
str += "\\P";
break;
default:
if (code.substr(0, 2) === "00")
str += "\\x" + code.substr(2);
else
str += json.substr(i, 6);
}
i += 5;
start = i + 1;
}
break;
case "n":
if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
i += 1;
} else {
str += json.slice(start, i) + "\n\n";
while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
str += "\n";
i += 2;
}
str += indent;
if (json[i + 2] === " ")
str += "\\";
i += 1;
start = i + 1;
}
break;
default:
i += 1;
}
}
str = start ? str + json.slice(start) : json;
return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value))
return doubleQuotedString(value, ctx);
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
const { singleQuote } = ctx.options;
let qs;
if (singleQuote === false)
qs = doubleQuotedString;
else {
const hasDouble = value.includes('"');
const hasSingle = value.includes("'");
if (hasDouble && !hasSingle)
qs = singleQuotedString;
else if (hasSingle && !hasDouble)
qs = doubleQuotedString;
else
qs = singleQuote ? singleQuotedString : doubleQuotedString;
}
return qs(value, ctx);
}
var blockEndNewlines;
try {
blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
} catch {
blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
if (!blockQuote || /\n[\t ]+$/.test(value)) {
return quotedString(value, ctx);
}
const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? " " : "");
const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
if (!value)
return literal ? "|\n" : ">\n";
let chomp;
let endStart;
for (endStart = value.length; endStart > 0; --endStart) {
const ch = value[endStart - 1];
if (ch !== "\n" && ch !== " " && ch !== " ")
break;
}
let end = value.substring(endStart);
const endNlPos = end.indexOf("\n");
if (endNlPos === -1) {
chomp = "-";
} else if (value === end || endNlPos !== end.length - 1) {
chomp = "+";
if (onChompKeep)
onChompKeep();
} else {
chomp = "";
}
if (end) {
value = value.slice(0, -end.length);
if (end[end.length - 1] === "\n")
end = end.slice(0, -1);
end = end.replace(blockEndNewlines, `$&${indent}`);
}
let startWithSpace = false;
let startEnd;
let startNlPos = -1;
for (startEnd = 0; startEnd < value.length; ++startEnd) {
const ch = value[startEnd];
if (ch === " ")
startWithSpace = true;
else if (ch === "\n")
startNlPos = startEnd;
else
break;
}
let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
if (start) {
value = value.substring(start.length);
start = start.replace(/\n+/g, `$&${indent}`);
}
const indentSize = indent ? "2" : "1";
let header = (startWithSpace ? indentSize : "") + chomp;
if (comment) {
header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
if (onComment)
onComment();
}
if (!literal) {
const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
let literalFallback = false;
const foldOptions = getFoldOptions(ctx, true);
if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
foldOptions.onOverflow = () => {
literalFallback = true;
};
}
const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
if (!literalFallback)
return `>${header}
${indent}${body}`;
}
value = value.replace(/\n+/g, `$&${indent}`);
return `|${header}
${indent}${start}${value}${end}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value } = item;
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) {
return quotedString(value, ctx);
}
if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
}
if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) {
return blockString(item, ctx, onComment, onChompKeep);
}
if (containsDocumentMarker(value)) {
if (indent === "") {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
} else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx);
}
}
const str = value.replace(/\n+/g, `$&
${indent}`);
if (actualString) {
const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
const { compat, tags } = ctx.doc.schema;
if (tags.some(test) || compat?.some(test))
return quotedString(value, ctx);
}
return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;
const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
let { type } = item;
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
type = Scalar.Scalar.QUOTE_DOUBLE;
}
const _stringify = (_type) => {
switch (_type) {
case Scalar.Scalar.BLOCK_FOLDED:
case Scalar.Scalar.BLOCK_LITERAL:
return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
case Scalar.Scalar.QUOTE_DOUBLE:
return doubleQuotedString(ss.value, ctx);
case Scalar.Scalar.QUOTE_SINGLE:
return singleQuotedString(ss.value, ctx);
case Scalar.Scalar.PLAIN:
return plainString(ss, ctx, onComment, onChompKeep);
default:
return null;
}
};
let res = _stringify(type);
if (res === null) {
const { defaultKeyType, defaultStringType } = ctx.options;
const t = implicitKey && defaultKeyType || defaultStringType;
res = _stringify(t);
if (res === null)
throw new Error(`Unsupported default string type ${t}`);
}
return res;
}
exports.stringifyString = stringifyString;
}
});
// node_modules/yaml/dist/stringify/stringify.js
var require_stringify = __commonJS({
"node_modules/yaml/dist/stringify/stringify.js"(exports) {
"use strict";
var anchors = require_anchors();
var identity = require_identity();
var stringifyComment = require_stringifyComment();
var stringifyString = require_stringifyString();
function createStringifyContext(doc, options) {
const opt = Object.assign({
blockQuote: true,
commentString: stringifyComment.stringifyComment,
defaultKeyType: null,
defaultStringType: "PLAIN",
directives: null,
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: "false",
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
nullStr: "null",
simpleKeys: false,
singleQuote: null,
trailingComma: false,
trueStr: "true",
verifyAliasOrder: true
}, doc.schema.toStringOptions, options);
let inFlow;
switch (opt.collectionStyle) {
case "block":
inFlow = false;
break;
case "flow":
inFlow = true;
break;
default:
inFlow = null;
}
return {
anchors: /* @__PURE__ */ new Set(),
doc,
flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
indent: "",
indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ",
inFlow,
options: opt
};
}
function getTagObject(tags, item) {
if (item.tag) {
const match = tags.filter((t) => t.tag === item.tag);
if (match.length > 0)
return match.find((t) => t.format === item.format) ?? match[0];
}
let tagObj = void 0;
let obj;
if (identity.isScalar(item)) {
obj = item.value;
let match = tags.filter((t) => t.identify?.(obj));
if (match.length > 1) {
const testMatch = match.filter((t) => t.test);
if (testMatch.length > 0)
match = testMatch;
}
tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
} else {
obj = item;
tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
}
if (!tagObj) {
const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
throw new Error(`Tag not resolved for ${name} value`);
}
return tagObj;
}
function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
if (!doc.directives)
return "";
const props = [];
const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
if (anchor && anchors.anchorIsValid(anchor)) {
anchors$1.add(anchor);
props.push(`&${anchor}`);
}
const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
if (tag)
props.push(doc.directives.tagString(tag));
return props.join(" ");
}
function stringify7(item, ctx, onComment, onChompKeep) {
if (identity.isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (identity.isAlias(item)) {
if (ctx.doc.directives)
return item.toString(ctx);
if (ctx.resolvedAliases?.has(item)) {
throw new TypeError(`Cannot stringify circular structure without alias nodes`);
} else {
if (ctx.resolvedAliases)
ctx.resolvedAliases.add(item);
else
ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
item = item.resolve(ctx.doc);
}
}
let tagObj = void 0;
const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
const props = stringifyProps(node, tagObj, ctx);
if (props.length > 0)
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}
exports.createStringifyContext = createStringifyContext;
exports.stringify = stringify7;
}
});
// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS({
"node_modules/yaml/dist/stringify/stringifyPair.js"(exports) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var stringify7 = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = identity.isNode(key) && key.comment || null;
if (simpleKeys) {
if (keyComment) {
throw new Error("With simple keys, key nodes cannot have comments");
}
if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") {
const msg = "With simple keys, collection cannot be used as a key value";
throw new Error(msg);
}
}
let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
ctx = Object.assign({}, ctx, {
allNullValues: false,
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
indent: indent + indentStep
});
let keyCommentDone = false;
let chompKeep = false;
let str = stringify7.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
if (!explicitKey && !ctx.inFlow && str.length > 1024) {
if (simpleKeys)
throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
explicitKey = true;
}
if (ctx.inFlow) {
if (allNullValues || value == null) {
if (keyCommentDone && onComment)
onComment();
return str === "" ? "?" : explicitKey ? `? ${str}` : str;
}
} else if (allNullValues && !simpleKeys || value == null && explicitKey) {
str = `? ${str}`;
if (keyComment && !keyCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
if (keyCommentDone)
keyComment = null;
if (explicitKey) {
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
str = `? ${str}
${indent}:`;
} else {
str = `${str}:`;
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
let vsb, vcb, valueComment;
if (identity.isNode(value)) {
vsb = !!value.spaceBefore;
vcb = value.commentBefore;
valueComment = value.comment;
} else {
vsb = false;
vcb = null;
valueComment = null;
if (value && typeof value === "object")
value = doc.createNode(value);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && identity.isScalar(value))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify7.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
let ws = " ";
if (keyComment || vsb || vcb) {
ws = vsb ? "\n" : "";
if (vcb) {
const cs = commentString(vcb);
ws += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
}
if (valueStr === "" && !ctx.inFlow) {
if (ws === "\n" && valueComment)
ws = "\n\n";
} else {
ws += `
${ctx.indent}`;
}
} else if (!explicitKey && identity.isCollection(value)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf("\n");
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === "&" || vs0 === "!")) {
let sp0 = valueStr.indexOf(" ");
if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
sp0 = valueStr.indexOf(" ", sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `
${ctx.indent}`;
}
} else if (valueStr === "" || valueStr[0] === "\n") {
ws = "";
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)
onComment();
} else if (valueComment && !valueCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
} else if (chompKeep && onChompKeep) {
onChompKeep();
}
return str;
}
exports.stringifyPair = stringifyPair;
}
});
// node_modules/yaml/dist/log.js
var require_log = __commonJS({
"node_modules/yaml/dist/log.js"(exports) {
"use strict";
var node_process = __require("process");
function debug(logLevel, ...messages) {
if (logLevel === "debug")
console.log(...messages);
}
function warn(logLevel, warning) {
if (logLevel === "debug" || logLevel === "warn") {
if (typeof node_process.emitWarning === "function")
node_process.emitWarning(warning);
else
console.warn(warning);
}
}
exports.debug = debug;
exports.warn = warn;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/merge.js
var require_merge = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/merge.js"(exports) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var MERGE_KEY = "<<";
var merge = {
identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
default: "key",
tag: "tag:yaml.org,2002:merge",
test: /^<<$/,
resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
addToJSMap: addMergeToJSMap
}),
stringify: () => MERGE_KEY
};
var isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default);
function addMergeToJSMap(ctx, map, value) {
const source = resolveAliasValue(ctx, value);
if (identity.isSeq(source))
for (const it of source.items)
mergeValue(ctx, map, it);
else if (Array.isArray(source))
for (const it of source)
mergeValue(ctx, map, it);
else
mergeValue(ctx, map, source);
}
function mergeValue(ctx, map, value) {
const source = resolveAliasValue(ctx, value);
if (!identity.isMap(source))
throw new Error("Merge sources must be maps or map aliases");
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value2] of srcMap) {
if (map instanceof Map) {
if (!map.has(key))
map.set(key, value2);
} else if (map instanceof Set) {
map.add(key);
} else if (!Object.prototype.hasOwnProperty.call(map, key)) {
Object.defineProperty(map, key, {
value: value2,
writable: true,
enumerable: true,
configurable: true
});
}
}
return map;
}
function resolveAliasValue(ctx, value) {
return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;
}
exports.addMergeToJSMap = addMergeToJSMap;
exports.isMergeKey = isMergeKey;
exports.merge = merge;
}
});
// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS({
"node_modules/yaml/dist/nodes/addPairToJSMap.js"(exports) {
"use strict";
var log = require_log();
var merge = require_merge();
var stringify7 = require_stringify();
var identity = require_identity();
var toJS = require_toJS();
function addPairToJSMap(ctx, map, { key, value }) {
if (identity.isNode(key) && key.addToJSMap)
key.addToJSMap(ctx, map, value);
else if (merge.isMergeKey(ctx, key))
merge.addMergeToJSMap(ctx, map, value);
else {
const jsKey = toJS.toJS(key, "", ctx);
if (map instanceof Map) {
map.set(jsKey, toJS.toJS(value, jsKey, ctx));
} else if (map instanceof Set) {
map.add(jsKey);
} else {
const stringKey = stringifyKey(key, jsKey, ctx);
const jsValue = toJS.toJS(value, stringKey, ctx);
if (stringKey in map)
Object.defineProperty(map, stringKey, {
value: jsValue,
writable: true,
enumerable: true,
configurable: true
});
else
map[stringKey] = jsValue;
}
}
return map;
}
function stringifyKey(key, jsKey, ctx) {
if (jsKey === null)
return "";
if (typeof jsKey !== "object")
return String(jsKey);
if (identity.isNode(key) && ctx?.doc) {
const strCtx = stringify7.createStringifyContext(ctx.doc, {});
strCtx.anchors = /* @__PURE__ */ new Set();
for (const node of ctx.anchors.keys())
strCtx.anchors.add(node.anchor);
strCtx.inFlow = true;
strCtx.inStringifyKey = true;
const strKey = key.toString(strCtx);
if (!ctx.mapKeyWarned) {
let jsonStr = JSON.stringify(strKey);
if (jsonStr.length > 40)
jsonStr = jsonStr.substring(0, 36) + '..."';
log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
ctx.mapKeyWarned = true;
}
return strKey;
}
return JSON.stringify(jsKey);
}
exports.addPairToJSMap = addPairToJSMap;
}
});
// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS({
"node_modules/yaml/dist/nodes/Pair.js"(exports) {
"use strict";
var createNode = require_createNode();
var stringifyPair = require_stringifyPair();
var addPairToJSMap = require_addPairToJSMap();
var identity = require_identity();
function createPair(key, value, ctx) {
const k = createNode.createNode(key, void 0, ctx);
const v = createNode.createNode(value, void 0, ctx);
return new Pair(k, v);
}
var Pair = class _Pair {
constructor(key, value = null) {
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
this.key = key;
this.value = value;
}
clone(schema) {
let { key, value } = this;
if (identity.isNode(key))
key = key.clone(schema);
if (identity.isNode(value))
value = value.clone(schema);
return new _Pair(key, value);
}
toJSON(_, ctx) {
const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
return addPairToJSMap.addPairToJSMap(ctx, pair, this);
}
toString(ctx, onComment, onChompKeep) {
return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
}
};
exports.Pair = Pair;
exports.createPair = createPair;
}
});
// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS({
"node_modules/yaml/dist/stringify/stringifyCollection.js"(exports) {
"use strict";
var identity = require_identity();
var stringify7 = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyCollection(collection, ctx, options) {
const flow = ctx.inFlow ?? collection.flow;
const stringify8 = flow ? stringifyFlowCollection : stringifyBlockCollection;
return stringify8(collection, ctx, options);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
const { indent, options: { commentString } } = ctx;
const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
let chompKeep = false;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment2 = null;
if (identity.isNode(item)) {
if (!chompKeep && item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment2 = item.comment;
} else if (identity.isPair(item)) {
const ik = identity.isNode(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
}
}
chompKeep = false;
let str2 = stringify7.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
if (comment2)
str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
if (chompKeep && comment2)
chompKeep = false;
lines.push(blockItemPrefix + str2);
}
let str;
if (lines.length === 0) {
str = flowChars.start + flowChars.end;
} else {
str = lines[0];
for (let i = 1; i < lines.length; ++i) {
const line = lines[i];
str += line ? `
${indent}${line}` : "\n";
}
}
if (comment) {
str += "\n" + stringifyComment.indentComment(commentString(comment), indent);
if (onComment)
onComment();
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
inFlow: true,
type: null
});
let reqNewline = false;
let linesAtValue = 0;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (identity.isNode(item)) {
if (item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
} else if (identity.isPair(item)) {
const ik = identity.isNode(item.key) ? item.key : null;
if (ik) {
if (ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, false);
if (ik.comment)
reqNewline = true;
}
const iv = identity.isNode(item.value) ? item.value : null;
if (iv) {
if (iv.comment)
comment = iv.comment;
if (iv.commentBefore)
reqNewline = true;
} else if (item.value == null && ik?.comment) {
comment = ik.comment;
}
}
if (comment)
reqNewline = true;
let str = stringify7.stringify(item, itemCtx, () => comment = null);
reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n"));
if (i < items.length - 1) {
str += ",";
} else if (ctx.options.trailingComma) {
if (ctx.options.lineWidth > 0) {
reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth);
}
if (reqNewline) {
str += ",";
}
}
if (comment)
str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
lines.push(str);
linesAtValue = lines.length;
}
const { start, end } = flowChars;
if (lines.length === 0) {
return start + end;
} else {
if (!reqNewline) {
const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
}
if (reqNewline) {
let str = start;
for (const line of lines)
str += line ? `
${indentStep}${indent}${line}` : "\n";
return `${str}
${indent}${end}`;
} else {
return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
}
}
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
if (comment && chompKeep)
comment = comment.replace(/^\n+/, "");
if (comment) {
const ic = stringifyComment.indentComment(commentString(comment), indent);
lines.push(ic.trimStart());
}
}
exports.stringifyCollection = stringifyCollection;
}
});
// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS({
"node_modules/yaml/dist/nodes/YAMLMap.js"(exports) {
"use strict";
var stringifyCollection = require_stringifyCollection();
var addPairToJSMap = require_addPairToJSMap();
var Collection = require_Collection();
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
function findPair(items, key) {
const k = identity.isScalar(key) ? key.value : key;
for (const it of items) {
if (identity.isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (identity.isScalar(it.key) && it.key.value === k)
return it;
}
}
return void 0;
}
var YAMLMap = class extends Collection.Collection {
static get tagName() {
return "tag:yaml.org,2002:map";
}
constructor(schema) {
super(identity.MAP, schema);
this.items = [];
}
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new this(schema);
const add = (key, value) => {
if (typeof replacer === "function")
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== void 0 || keepUndefined)
map.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
} else if (obj && typeof obj === "object") {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === "function") {
map.items.sort(schema.sortMapEntries);
}
return map;
}
/**
* Adds a value to the collection.
*
* @param overwrite - If not set `true`, using a key that is already in the
* collection will throw. Otherwise, overwrites the previous value.
*/
add(pair, overwrite) {
let _pair;
if (identity.isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== "object" || !("key" in pair)) {
_pair = new Pair.Pair(pair, pair?.value);
} else
_pair = new Pair.Pair(pair.key, pair.value);
const prev = findPair(this.items, _pair.key);
const sortEntries = this.schema?.sortMapEntries;
if (prev) {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
} else if (sortEntries) {
const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
if (i === -1)
this.items.push(_pair);
else
this.items.splice(i, 0, _pair);
} else {
this.items.push(_pair);
}
}
delete(key) {
const it = findPair(this.items, key);
if (!it)
return false;
const del = this.items.splice(this.items.indexOf(it), 1);
return del.length > 0;
}
get(key, keepScalar) {
const it = findPair(this.items, key);
const node = it?.value;
return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0;
}
has(key) {
return !!findPair(this.items, key);
}
set(key, value) {
this.add(new Pair.Pair(key, value), true);
}
/**
* @param ctx - Conversion context, originally set in Document#toJS()
* @param {Class} Type - If set, forces the returned collection type
* @returns Instance of Type, Map, or Object
*/
toJSON(_, ctx, Type) {
const map = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
if (ctx?.onCreate)
ctx.onCreate(map);
for (const item of this.items)
addPairToJSMap.addPairToJSMap(ctx, map, item);
return map;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!identity.isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))
ctx = Object.assign({}, ctx, { allNullValues: true });
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: "",
flowChars: { start: "{", end: "}" },
itemIndent: ctx.indent || "",
onChompKeep,
onComment
});
}
};
exports.YAMLMap = YAMLMap;
exports.findPair = findPair;
}
});
// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS({
"node_modules/yaml/dist/schema/common/map.js"(exports) {
"use strict";
var identity = require_identity();
var YAMLMap = require_YAMLMap();
var map = {
collection: "map",
default: true,
nodeClass: YAMLMap.YAMLMap,
tag: "tag:yaml.org,2002:map",
resolve(map2, onError) {
if (!identity.isMap(map2))
onError("Expected a mapping for this tag");
return map2;
},
createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
};
exports.map = map;
}
});
// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS({
"node_modules/yaml/dist/nodes/YAMLSeq.js"(exports) {
"use strict";
var createNode = require_createNode();
var stringifyCollection = require_stringifyCollection();
var Collection = require_Collection();
var identity = require_identity();
var Scalar = require_Scalar();
var toJS = require_toJS();
var YAMLSeq = class extends Collection.Collection {
static get tagName() {
return "tag:yaml.org,2002:seq";
}
constructor(schema) {
super(identity.SEQ, schema);
this.items = [];
}
add(value) {
this.items.push(value);
}
/**
* Removes a value from the collection.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*
* @returns `true` if the item was found and removed.
*/
delete(key) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return false;
const del = this.items.splice(idx, 1);
return del.length > 0;
}
get(key, keepScalar) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return void 0;
const it = this.items[idx];
return !keepScalar && identity.isScalar(it) ? it.value : it;
}
/**
* Checks if the collection includes a value with the key `key`.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*/
has(key) {
const idx = asItemIndex(key);
return typeof idx === "number" && idx < this.items.length;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*
* If `key` does not contain a representation of an integer, this will throw.
* It may be wrapped in a `Scalar`.
*/
set(key, value) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (identity.isScalar(prev) && Scalar.isScalarValue(value))
prev.value = value;
else
this.items[idx] = value;
}
toJSON(_, ctx) {
const seq = [];
if (ctx?.onCreate)
ctx.onCreate(seq);
let i = 0;
for (const item of this.items)
seq.push(toJS.toJS(item, String(i++), ctx));
return seq;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: "- ",
flowChars: { start: "[", end: "]" },
itemIndent: (ctx.indent || "") + " ",
onChompKeep,
onComment
});
}
static from(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new this(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === "function") {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, void 0, ctx));
}
}
return seq;
}
};
function asItemIndex(key) {
let idx = identity.isScalar(key) ? key.value : key;
if (idx && typeof idx === "string")
idx = Number(idx);
return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}
exports.YAMLSeq = YAMLSeq;
}
});
// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS({
"node_modules/yaml/dist/schema/common/seq.js"(exports) {
"use strict";
var identity = require_identity();
var YAMLSeq = require_YAMLSeq();
var seq = {
collection: "seq",
default: true,
nodeClass: YAMLSeq.YAMLSeq,
tag: "tag:yaml.org,2002:seq",
resolve(seq2, onError) {
if (!identity.isSeq(seq2))
onError("Expected a sequence for this tag");
return seq2;
},
createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
};
exports.seq = seq;
}
});
// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS({
"node_modules/yaml/dist/schema/common/string.js"(exports) {
"use strict";
var stringifyString = require_stringifyString();
var string = {
identify: (value) => typeof value === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify(item, ctx, onComment, onChompKeep) {
ctx = Object.assign({ actualString: true }, ctx);
return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
}
};
exports.string = string;
}
});
// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS({
"node_modules/yaml/dist/schema/common/null.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var nullTag = {
identify: (value) => value == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^(?:~|[Nn]ull|NULL)?$/,
resolve: () => new Scalar.Scalar(null),
stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
};
exports.nullTag = nullTag;
}
});
// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS({
"node_modules/yaml/dist/schema/core/bool.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var boolTag = {
identify: (value) => typeof value === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
stringify({ source, value }, ctx) {
if (source && boolTag.test.test(source)) {
const sv = source[0] === "t" || source[0] === "T";
if (value === sv)
return source;
}
return value ? ctx.options.trueStr : ctx.options.falseStr;
}
};
exports.boolTag = boolTag;
}
});
// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS({
"node_modules/yaml/dist/stringify/stringifyNumber.js"(exports) {
"use strict";
function stringifyNumber({ format, minFractionDigits, tag, value }) {
if (typeof value === "bigint")
return String(value);
const num = typeof value === "number" ? value : Number(value);
if (!isFinite(num))
return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
let n = Object.is(value, -0) ? "-0" : JSON.stringify(value);
if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) {
let i = n.indexOf(".");
if (i < 0) {
i = n.length;
n += ".";
}
let d = minFractionDigits - (n.length - i - 1);
while (d-- > 0)
n += "0";
}
return n;
}
exports.stringifyNumber = stringifyNumber;
}
});
// node_modules/yaml/dist/schema/core/float.js
var require_float = __commonJS({
"node_modules/yaml/dist/schema/core/float.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var stringifyNumber = require_stringifyNumber();
var floatNaN = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
var floatExp = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
var float = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str));
const dot = str.indexOf(".");
if (dot !== -1 && str[str.length - 1] === "0")
node.minFractionDigits = str.length - dot - 1;
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports.float = float;
exports.floatExp = floatExp;
exports.floatNaN = floatNaN;
}
});
// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS({
"node_modules/yaml/dist/schema/core/int.js"(exports) {
"use strict";
var stringifyNumber = require_stringifyNumber();
var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
function intStringify(node, radix, prefix) {
const { value } = node;
if (intIdentify(value) && value >= 0)
return prefix + value.toString(radix);
return stringifyNumber.stringifyNumber(node);
}
var intOct = {
identify: (value) => intIdentify(value) && value >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^0o[0-7]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
stringify: (node) => intStringify(node, 8, "0o")
};
var int = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9]+$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
var intHex = {
identify: (value) => intIdentify(value) && value >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^0x[0-9a-fA-F]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node) => intStringify(node, 16, "0x")
};
exports.int = int;
exports.intHex = intHex;
exports.intOct = intOct;
}
});
// node_modules/yaml/dist/schema/core/schema.js
var require_schema2 = __commonJS({
"node_modules/yaml/dist/schema/core/schema.js"(exports) {
"use strict";
var map = require_map();
var _null = require_null();
var seq = require_seq();
var string = require_string();
var bool = require_bool();
var float = require_float();
var int = require_int();
var schema = [
map.map,
seq.seq,
string.string,
_null.nullTag,
bool.boolTag,
int.intOct,
int.int,
int.intHex,
float.floatNaN,
float.floatExp,
float.float
];
exports.schema = schema;
}
});
// node_modules/yaml/dist/schema/json/schema.js
var require_schema3 = __commonJS({
"node_modules/yaml/dist/schema/json/schema.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var map = require_map();
var seq = require_seq();
function intIdentify(value) {
return typeof value === "bigint" || Number.isInteger(value);
}
var stringifyJSON = ({ value }) => JSON.stringify(value);
var jsonScalars = [
{
identify: (value) => typeof value === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify: stringifyJSON
},
{
identify: (value) => value == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^null$/,
resolve: () => null,
stringify: stringifyJSON
},
{
identify: (value) => typeof value === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^true$|^false$/,
resolve: (str) => str === "true",
stringify: stringifyJSON
},
{
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^-?(?:0|[1-9][0-9]*)$/,
resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
},
{
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
resolve: (str) => parseFloat(str),
stringify: stringifyJSON
}
];
var jsonError = {
default: true,
tag: "",
test: /^/,
resolve(str, onError) {
onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
return str;
}
};
var schema = [map.map, seq.seq].concat(jsonScalars, jsonError);
exports.schema = schema;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports) {
"use strict";
var node_buffer = __require("buffer");
var Scalar = require_Scalar();
var stringifyString = require_stringifyString();
var binary = {
identify: (value) => value instanceof Uint8Array,
// Buffer inherits from Uint8Array
default: false,
tag: "tag:yaml.org,2002:binary",
/**
* Returns a Buffer in node and an Uint8Array in browsers
*
* To use the resulting buffer as an image, you'll want to do something like:
*
* const blob = new Blob([buffer], { type: 'image/jpeg' })
* document.querySelector('#photo').src = URL.createObjectURL(blob)
*/
resolve(src, onError) {
if (typeof node_buffer.Buffer === "function") {
return node_buffer.Buffer.from(src, "base64");
} else if (typeof atob === "function") {
const str = atob(src.replace(/[\n\r]/g, ""));
const buffer = new Uint8Array(str.length);
for (let i = 0; i < str.length; ++i)
buffer[i] = str.charCodeAt(i);
return buffer;
} else {
onError("This environment does not support reading binary tags; either Buffer or atob is required");
return src;
}
},
stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
if (!value)
return "";
const buf = value;
let str;
if (typeof node_buffer.Buffer === "function") {
str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
} else if (typeof btoa === "function") {
let s = "";
for (let i = 0; i < buf.length; ++i)
s += String.fromCharCode(buf[i]);
str = btoa(s);
} else {
throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
}
type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
const n = Math.ceil(str.length / lineWidth);
const lines = new Array(n);
for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
lines[i] = str.substr(o, lineWidth);
}
str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " ");
}
return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
}
};
exports.binary = binary;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports) {
"use strict";
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLSeq = require_YAMLSeq();
function resolvePairs(seq, onError) {
if (identity.isSeq(seq)) {
for (let i = 0; i < seq.items.length; ++i) {
let item = seq.items[i];
if (identity.isPair(item))
continue;
else if (identity.isMap(item)) {
if (item.items.length > 1)
onError("Each pair must have its own sequence indicator");
const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
if (item.commentBefore)
pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
if (item.comment) {
const cn = pair.value ?? pair.key;
cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
}
item = pair;
}
seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
}
} else
onError("Expected a sequence for this tag");
return seq;
}
function createPairs(schema, iterable, ctx) {
const { replacer } = ctx;
const pairs2 = new YAMLSeq.YAMLSeq(schema);
pairs2.tag = "tag:yaml.org,2002:pairs";
let i = 0;
if (iterable && Symbol.iterator in Object(iterable))
for (let it of iterable) {
if (typeof replacer === "function")
it = replacer.call(iterable, String(i++), it);
let key, value;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = it[1];
} else
throw new TypeError(`Expected [key, value] tuple: ${it}`);
} else if (it && it instanceof Object) {
const keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value = it[key];
} else {
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
}
} else {
key = it;
}
pairs2.items.push(Pair.createPair(key, value, ctx));
}
return pairs2;
}
var pairs = {
collection: "seq",
default: false,
tag: "tag:yaml.org,2002:pairs",
resolve: resolvePairs,
createNode: createPairs
};
exports.createPairs = createPairs;
exports.pairs = pairs;
exports.resolvePairs = resolvePairs;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports) {
"use strict";
var identity = require_identity();
var toJS = require_toJS();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var pairs = require_pairs();
var YAMLOMap = class _YAMLOMap extends YAMLSeq.YAMLSeq {
constructor() {
super();
this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
this.tag = _YAMLOMap.tag;
}
/**
* If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
* but TypeScript won't allow widening the signature of a child method.
*/
toJSON(_, ctx) {
if (!ctx)
return super.toJSON(_);
const map = /* @__PURE__ */ new Map();
if (ctx?.onCreate)
ctx.onCreate(map);
for (const pair of this.items) {
let key, value;
if (identity.isPair(pair)) {
key = toJS.toJS(pair.key, "", ctx);
value = toJS.toJS(pair.value, key, ctx);
} else {
key = toJS.toJS(pair, "", ctx);
}
if (map.has(key))
throw new Error("Ordered maps must not include duplicate keys");
map.set(key, value);
}
return map;
}
static from(schema, iterable, ctx) {
const pairs$1 = pairs.createPairs(schema, iterable, ctx);
const omap2 = new this();
omap2.items = pairs$1.items;
return omap2;
}
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
collection: "seq",
identify: (value) => value instanceof Map,
nodeClass: YAMLOMap,
default: false,
tag: "tag:yaml.org,2002:omap",
resolve(seq, onError) {
const pairs$1 = pairs.resolvePairs(seq, onError);
const seenKeys = [];
for (const { key } of pairs$1.items) {
if (identity.isScalar(key)) {
if (seenKeys.includes(key.value)) {
onError(`Ordered maps must not include duplicate keys: ${key.value}`);
} else {
seenKeys.push(key.value);
}
}
}
return Object.assign(new YAMLOMap(), pairs$1);
},
createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
};
exports.YAMLOMap = YAMLOMap;
exports.omap = omap;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports) {
"use strict";
var Scalar = require_Scalar();
function boolStringify({ value, source }, ctx) {
const boolObj = value ? trueTag : falseTag;
if (source && boolObj.test.test(source))
return source;
return value ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
identify: (value) => value === true,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
resolve: () => new Scalar.Scalar(true),
stringify: boolStringify
};
var falseTag = {
identify: (value) => value === false,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
resolve: () => new Scalar.Scalar(false),
stringify: boolStringify
};
exports.falseTag = falseTag;
exports.trueTag = trueTag;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float2 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var stringifyNumber = require_stringifyNumber();
var floatNaN = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
var floatExp = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str.replace(/_/g, "")),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
var float = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
const dot = str.indexOf(".");
if (dot !== -1) {
const f = str.substring(dot + 1).replace(/_/g, "");
if (f[f.length - 1] === "0")
node.minFractionDigits = f.length;
}
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports.float = float;
exports.floatExp = floatExp;
exports.floatNaN = floatNaN;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports) {
"use strict";
var stringifyNumber = require_stringifyNumber();
var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
function intResolve(str, offset, radix, { intAsBigInt }) {
const sign = str[0];
if (sign === "-" || sign === "+")
offset += 1;
str = str.substring(offset).replace(/_/g, "");
if (intAsBigInt) {
switch (radix) {
case 2:
str = `0b${str}`;
break;
case 8:
str = `0o${str}`;
break;
case 16:
str = `0x${str}`;
break;
}
const n2 = BigInt(str);
return sign === "-" ? BigInt(-1) * n2 : n2;
}
const n = parseInt(str, radix);
return sign === "-" ? -1 * n : n;
}
function intStringify(node, radix, prefix) {
const { value } = node;
if (intIdentify(value)) {
const str = value.toString(radix);
return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
}
return stringifyNumber.stringifyNumber(node);
}
var intBin = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "BIN",
test: /^[-+]?0b[0-1_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
stringify: (node) => intStringify(node, 2, "0b")
};
var intOct = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^[-+]?0[0-7_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
stringify: (node) => intStringify(node, 8, "0")
};
var int = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9][0-9_]*$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
var intHex = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^[-+]?0x[0-9a-fA-F_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node) => intStringify(node, 16, "0x")
};
exports.int = int;
exports.intBin = intBin;
exports.intHex = intHex;
exports.intOct = intOct;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports) {
"use strict";
var identity = require_identity();
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var YAMLSet = class _YAMLSet extends YAMLMap.YAMLMap {
constructor(schema) {
super(schema);
this.tag = _YAMLSet.tag;
}
add(key) {
let pair;
if (identity.isPair(key))
pair = key;
else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
pair = new Pair.Pair(key.key, null);
else
pair = new Pair.Pair(key, null);
const prev = YAMLMap.findPair(this.items, pair.key);
if (!prev)
this.items.push(pair);
}
/**
* If `keepPair` is `true`, returns the Pair matching `key`.
* Otherwise, returns the value of that Pair's key.
*/
get(key, keepPair) {
const pair = YAMLMap.findPair(this.items, key);
return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair;
}
set(key, value) {
if (typeof value !== "boolean")
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
const prev = YAMLMap.findPair(this.items, key);
if (prev && !value) {
this.items.splice(this.items.indexOf(prev), 1);
} else if (!prev && value) {
this.items.push(new Pair.Pair(key));
}
}
toJSON(_, ctx) {
return super.toJSON(_, ctx, Set);
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
if (this.hasAllNullValues(true))
return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
else
throw new Error("Set items must all have null values");
}
static from(schema, iterable, ctx) {
const { replacer } = ctx;
const set2 = new this(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === "function")
value = replacer.call(iterable, value, value);
set2.items.push(Pair.createPair(value, null, ctx));
}
return set2;
}
};
YAMLSet.tag = "tag:yaml.org,2002:set";
var set = {
collection: "map",
identify: (value) => value instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: "tag:yaml.org,2002:set",
createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
resolve(map, onError) {
if (identity.isMap(map)) {
if (map.hasAllNullValues(true))
return Object.assign(new YAMLSet(), map);
else
onError("Set items must all have null values");
} else
onError("Expected a mapping for this tag");
return map;
}
};
exports.YAMLSet = YAMLSet;
exports.set = set;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports) {
"use strict";
var stringifyNumber = require_stringifyNumber();
function parseSexagesimal(str, asBigInt) {
const sign = str[0];
const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
const num = (n) => asBigInt ? BigInt(n) : Number(n);
const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node) {
let { value } = node;
let num = (n) => n;
if (typeof value === "bigint")
num = (n) => BigInt(n);
else if (isNaN(value) || !isFinite(value))
return stringifyNumber.stringifyNumber(node);
let sign = "";
if (value < 0) {
sign = "-";
value *= num(-1);
}
const _60 = num(60);
const parts = [value % _60];
if (value < 60) {
parts.unshift(0);
} else {
value = (value - parts[0]) / _60;
parts.unshift(value % _60);
if (value >= 60) {
value = (value - parts[0]) / _60;
parts.unshift(value);
}
}
return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
identify: (value) => typeof value === "bigint" || Number.isInteger(value),
default: true,
tag: "tag:yaml.org,2002:int",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
stringify: stringifySexagesimal
};
var floatTime = {
identify: (value) => typeof value === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
resolve: (str) => parseSexagesimal(str, false),
stringify: stringifySexagesimal
};
var timestamp = {
identify: (value) => value instanceof Date,
default: true,
tag: "tag:yaml.org,2002:timestamp",
// If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
// may be omitted altogether, resulting in a date format. In such a case, the time part is
// assumed to be 00:00:00Z (start of day, UTC).
test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
resolve(str) {
const match = str.match(timestamp.test);
if (!match)
throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
const [, year, month, day, hour, minute, second] = match.map(Number);
const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
const tz = match[8];
if (tz && tz !== "Z") {
let d = parseSexagesimal(tz, false);
if (Math.abs(d) < 30)
d *= 60;
date -= 6e4 * d;
}
return new Date(date);
},
stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
};
exports.floatTime = floatTime;
exports.intTime = intTime;
exports.timestamp = timestamp;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema4 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports) {
"use strict";
var map = require_map();
var _null = require_null();
var seq = require_seq();
var string = require_string();
var binary = require_binary();
var bool = require_bool2();
var float = require_float2();
var int = require_int2();
var merge = require_merge();
var omap = require_omap();
var pairs = require_pairs();
var set = require_set();
var timestamp = require_timestamp();
var schema = [
map.map,
seq.seq,
string.string,
_null.nullTag,
bool.trueTag,
bool.falseTag,
int.intBin,
int.intOct,
int.int,
int.intHex,
float.floatNaN,
float.floatExp,
float.float,
binary.binary,
merge.merge,
omap.omap,
pairs.pairs,
set.set,
timestamp.intTime,
timestamp.floatTime,
timestamp.timestamp
];
exports.schema = schema;
}
});
// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS({
"node_modules/yaml/dist/schema/tags.js"(exports) {
"use strict";
var map = require_map();
var _null = require_null();
var seq = require_seq();
var string = require_string();
var bool = require_bool();
var float = require_float();
var int = require_int();
var schema = require_schema2();
var schema$1 = require_schema3();
var binary = require_binary();
var merge = require_merge();
var omap = require_omap();
var pairs = require_pairs();
var schema$2 = require_schema4();
var set = require_set();
var timestamp = require_timestamp();
var schemas = /* @__PURE__ */ new Map([
["core", schema.schema],
["failsafe", [map.map, seq.seq, string.string]],
["json", schema$1.schema],
["yaml11", schema$2.schema],
["yaml-1.1", schema$2.schema]
]);
var tagsByName = {
binary: binary.binary,
bool: bool.boolTag,
float: float.float,
floatExp: float.floatExp,
floatNaN: float.floatNaN,
floatTime: timestamp.floatTime,
int: int.int,
intHex: int.intHex,
intOct: int.intOct,
intTime: timestamp.intTime,
map: map.map,
merge: merge.merge,
null: _null.nullTag,
omap: omap.omap,
pairs: pairs.pairs,
seq: seq.seq,
set: set.set,
timestamp: timestamp.timestamp
};
var coreKnownTags = {
"tag:yaml.org,2002:binary": binary.binary,
"tag:yaml.org,2002:merge": merge.merge,
"tag:yaml.org,2002:omap": omap.omap,
"tag:yaml.org,2002:pairs": pairs.pairs,
"tag:yaml.org,2002:set": set.set,
"tag:yaml.org,2002:timestamp": timestamp.timestamp
};
function getTags(customTags, schemaName, addMergeTag) {
const schemaTags = schemas.get(schemaName);
if (schemaTags && !customTags) {
return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice();
}
let tags = schemaTags;
if (!tags) {
if (Array.isArray(customTags))
tags = [];
else {
const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
}
}
if (Array.isArray(customTags)) {
for (const tag of customTags)
tags = tags.concat(tag);
} else if (typeof customTags === "function") {
tags = customTags(tags.slice());
}
if (addMergeTag)
tags = tags.concat(merge.merge);
return tags.reduce((tags2, tag) => {
const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
if (!tagObj) {
const tagName = JSON.stringify(tag);
const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
}
if (!tags2.includes(tagObj))
tags2.push(tagObj);
return tags2;
}, []);
}
exports.coreKnownTags = coreKnownTags;
exports.getTags = getTags;
}
});
// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS({
"node_modules/yaml/dist/schema/Schema.js"(exports) {
"use strict";
var identity = require_identity();
var map = require_map();
var seq = require_seq();
var string = require_string();
var tags = require_tags();
var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
var Schema = class _Schema {
constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null;
this.name = typeof schema === "string" && schema || "core";
this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
this.tags = tags.getTags(customTags, this.name, merge);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, identity.MAP, { value: map.map });
Object.defineProperty(this, identity.SCALAR, { value: string.string });
Object.defineProperty(this, identity.SEQ, { value: seq.seq });
this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
}
clone() {
const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
copy.tags = this.tags.slice();
return copy;
}
};
exports.Schema = Schema;
}
});
// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS({
"node_modules/yaml/dist/stringify/stringifyDocument.js"(exports) {
"use strict";
var identity = require_identity();
var stringify7 = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyDocument(doc, options) {
const lines = [];
let hasDirectives = options.directives === true;
if (options.directives !== false && doc.directives) {
const dir = doc.directives.toString(doc);
if (dir) {
lines.push(dir);
hasDirectives = true;
} else if (doc.directives.docStart)
hasDirectives = true;
}
if (hasDirectives)
lines.push("---");
const ctx = stringify7.createStringifyContext(doc, options);
const { commentString } = ctx.options;
if (doc.commentBefore) {
if (lines.length !== 1)
lines.unshift("");
const cs = commentString(doc.commentBefore);
lines.unshift(stringifyComment.indentComment(cs, ""));
}
let chompKeep = false;
let contentComment = null;
if (doc.contents) {
if (identity.isNode(doc.contents)) {
if (doc.contents.spaceBefore && hasDirectives)
lines.push("");
if (doc.contents.commentBefore) {
const cs = commentString(doc.contents.commentBefore);
lines.push(stringifyComment.indentComment(cs, ""));
}
ctx.forceBlockIndent = !!doc.comment;
contentComment = doc.contents.comment;
}
const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
let body = stringify7.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
if (contentComment)
body += stringifyComment.lineComment(body, "", commentString(contentComment));
if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
lines[lines.length - 1] = `--- ${body}`;
} else
lines.push(body);
} else {
lines.push(stringify7.stringify(doc.contents, ctx));
}
if (doc.directives?.docEnd) {
if (doc.comment) {
const cs = commentString(doc.comment);
if (cs.includes("\n")) {
lines.push("...");
lines.push(stringifyComment.indentComment(cs, ""));
} else {
lines.push(`... ${cs}`);
}
} else {
lines.push("...");
}
} else {
let dc = doc.comment;
if (dc && chompKeep)
dc = dc.replace(/^\n+/, "");
if (dc) {
if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
lines.push("");
lines.push(stringifyComment.indentComment(commentString(dc), ""));
}
}
return lines.join("\n") + "\n";
}
exports.stringifyDocument = stringifyDocument;
}
});
// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS({
"node_modules/yaml/dist/doc/Document.js"(exports) {
"use strict";
var Alias = require_Alias();
var Collection = require_Collection();
var identity = require_identity();
var Pair = require_Pair();
var toJS = require_toJS();
var Schema = require_Schema();
var stringifyDocument = require_stringifyDocument();
var anchors = require_anchors();
var applyReviver = require_applyReviver();
var createNode = require_createNode();
var directives = require_directives();
var Document = class _Document {
constructor(value, replacer, options) {
this.commentBefore = null;
this.comment = null;
this.errors = [];
this.warnings = [];
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options === void 0 && replacer) {
options = replacer;
replacer = void 0;
}
const opt = Object.assign({
intAsBigInt: false,
keepSourceTokens: false,
logLevel: "warn",
prettyErrors: true,
strict: true,
stringKeys: false,
uniqueKeys: true,
version: "1.2"
}, options);
this.options = opt;
let { version } = opt;
if (options?._directives) {
this.directives = options._directives.atDocument();
if (this.directives.yaml.explicit)
version = this.directives.yaml.version;
} else
this.directives = new directives.Directives({ version });
this.setSchema(version, options);
this.contents = value === void 0 ? null : this.createNode(value, _replacer, options);
}
/**
* Create a deep copy of this Document and its contents.
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone() {
const copy = Object.create(_Document.prototype, {
[identity.NODE_TYPE]: { value: identity.DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
copy.errors = this.errors.slice();
copy.warnings = this.warnings.slice();
copy.options = Object.assign({}, this.options);
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** Adds a value to the document. */
add(value) {
if (assertCollection(this.contents))
this.contents.add(value);
}
/** Adds a value to the document. */
addIn(path, value) {
if (assertCollection(this.contents))
this.contents.addIn(path, value);
}
/**
* Create a new `Alias` node, ensuring that the target `node` has the required anchor.
*
* If `node` already has an anchor, `name` is ignored.
* Otherwise, the `node.anchor` value will be set to `name`,
* or if an anchor with that name is already present in the document,
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node, name) {
if (!node.anchor) {
const prev = anchors.anchorNames(this);
node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
!name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name;
}
return new Alias.Alias(node.anchor);
}
createNode(value, replacer, options) {
let _replacer = void 0;
if (typeof replacer === "function") {
value = replacer.call({ "": value }, "", value);
_replacer = replacer;
} else if (Array.isArray(replacer)) {
const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
const asStr = replacer.filter(keyToStr).map(String);
if (asStr.length > 0)
replacer = replacer.concat(asStr);
_replacer = replacer;
} else if (options === void 0 && replacer) {
options = replacer;
replacer = void 0;
}
const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(
this,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
anchorPrefix || "a"
);
const ctx = {
aliasDuplicateObjects: aliasDuplicateObjects ?? true,
keepUndefined: keepUndefined ?? false,
onAnchor,
onTagObj,
replacer: _replacer,
schema: this.schema,
sourceObjects
};
const node = createNode.createNode(value, tag, ctx);
if (flow && identity.isCollection(node))
node.flow = true;
setAnchors();
return node;
}
/**
* Convert a key and a value into a `Pair` using the current schema,
* recursively wrapping all values as `Scalar` or `Collection` nodes.
*/
createPair(key, value, options = {}) {
const k = this.createNode(key, null, options);
const v = this.createNode(value, null, options);
return new Pair.Pair(k, v);
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
delete(key) {
return assertCollection(this.contents) ? this.contents.delete(key) : false;
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
deleteIn(path) {
if (Collection.isEmptyPath(path)) {
if (this.contents == null)
return false;
this.contents = null;
return true;
}
return assertCollection(this.contents) ? this.contents.deleteIn(path) : false;
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key, keepScalar) {
return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0;
}
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path, keepScalar) {
if (Collection.isEmptyPath(path))
return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0;
}
/**
* Checks if the document includes a value with the key `key`.
*/
has(key) {
return identity.isCollection(this.contents) ? this.contents.has(key) : false;
}
/**
* Checks if the document includes a value at `path`.
*/
hasIn(path) {
if (Collection.isEmptyPath(path))
return this.contents !== void 0;
return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
set(key, value) {
if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, [key], value);
} else if (assertCollection(this.contents)) {
this.contents.set(key, value);
}
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
if (Collection.isEmptyPath(path)) {
this.contents = value;
} else if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
} else if (assertCollection(this.contents)) {
this.contents.setIn(path, value);
}
}
/**
* Change the YAML version and schema used by the document.
* A `null` version disables support for directives, explicit tags, anchors, and aliases.
* It also requires the `schema` option to be given as a `Schema` instance value.
*
* Overrides all previously set schema options.
*/
setSchema(version, options = {}) {
if (typeof version === "number")
version = String(version);
let opt;
switch (version) {
case "1.1":
if (this.directives)
this.directives.yaml.version = "1.1";
else
this.directives = new directives.Directives({ version: "1.1" });
opt = { resolveKnownTags: false, schema: "yaml-1.1" };
break;
case "1.2":
case "next":
if (this.directives)
this.directives.yaml.version = version;
else
this.directives = new directives.Directives({ version });
opt = { resolveKnownTags: true, schema: "core" };
break;
case null:
if (this.directives)
delete this.directives;
opt = null;
break;
default: {
const sv = JSON.stringify(version);
throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
}
}
if (options.schema instanceof Object)
this.schema = options.schema;
else if (opt)
this.schema = new Schema.Schema(Object.assign(opt, options));
else
throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
}
// json & jsonArg are only used from toJSON()
toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
const ctx = {
anchors: /* @__PURE__ */ new Map(),
doc: this,
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
}
/**
* A JSON representation of the document `contents`.
*
* @param jsonArg Used by `JSON.stringify` to indicate the array index or
* property name.
*/
toJSON(jsonArg, onAnchor) {
return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
}
/** A YAML representation of the document. */
toString(options = {}) {
if (this.errors.length > 0)
throw new Error("Document with errors cannot be stringified");
if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
const s = JSON.stringify(options.indent);
throw new Error(`"indent" option must be a positive integer, not ${s}`);
}
return stringifyDocument.stringifyDocument(this, options);
}
};
function assertCollection(contents) {
if (identity.isCollection(contents))
return true;
throw new Error("Expected a YAML collection as document contents");
}
exports.Document = Document;
}
});
// node_modules/yaml/dist/errors.js
var require_errors2 = __commonJS({
"node_modules/yaml/dist/errors.js"(exports) {
"use strict";
var YAMLError = class extends Error {
constructor(name, pos, code, message) {
super();
this.name = name;
this.code = code;
this.message = message;
this.pos = pos;
}
};
var YAMLParseError = class extends YAMLError {
constructor(pos, code, message) {
super("YAMLParseError", pos, code, message);
}
};
var YAMLWarning = class extends YAMLError {
constructor(pos, code, message) {
super("YAMLWarning", pos, code, message);
}
};
var prettifyError = (src, lc) => (error) => {
if (error.pos[0] === -1)
return;
error.linePos = error.pos.map((pos) => lc.linePos(pos));
const { line, col } = error.linePos[0];
error.message += ` at line ${line}, column ${col}`;
let ci = col - 1;
let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
if (ci >= 60 && lineStr.length > 80) {
const trimStart = Math.min(ci - 39, lineStr.length - 79);
lineStr = "\u2026" + lineStr.substring(trimStart);
ci -= trimStart - 1;
}
if (lineStr.length > 80)
lineStr = lineStr.substring(0, 79) + "\u2026";
if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
if (prev.length > 80)
prev = prev.substring(0, 79) + "\u2026\n";
lineStr = prev + lineStr;
}
if (/[^ ]/.test(lineStr)) {
let count = 1;
const end = error.linePos[1];
if (end?.line === line && end.col > col) {
count = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = " ".repeat(ci) + "^".repeat(count);
error.message += `:
${lineStr}
${pointer}
`;
}
};
exports.YAMLError = YAMLError;
exports.YAMLParseError = YAMLParseError;
exports.YAMLWarning = YAMLWarning;
exports.prettifyError = prettifyError;
}
});
// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS({
"node_modules/yaml/dist/compose/resolve-props.js"(exports) {
"use strict";
function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
let spaceBefore = false;
let atNewline = startOnNewline;
let hasSpace = startOnNewline;
let comment = "";
let commentSep = "";
let hasNewline = false;
let reqSpace = false;
let tab = null;
let anchor = null;
let tag = null;
let newlineAfterProp = null;
let comma = null;
let found = null;
let start = null;
for (const token of tokens) {
if (reqSpace) {
if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
reqSpace = false;
}
if (tab) {
if (atNewline && token.type !== "comment" && token.type !== "newline") {
onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
}
tab = null;
}
switch (token.type) {
case "space":
if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) {
tab = token;
}
hasSpace = true;
break;
case "comment": {
if (!hasSpace)
onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = token.source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += commentSep + cb;
commentSep = "";
atNewline = false;
break;
}
case "newline":
if (atNewline) {
if (comment)
comment += token.source;
else if (!found || indicator !== "seq-item-ind")
spaceBefore = true;
} else
commentSep += token.source;
atNewline = true;
hasNewline = true;
if (anchor || tag)
newlineAfterProp = token;
hasSpace = true;
break;
case "anchor":
if (anchor)
onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
if (token.source.endsWith(":"))
onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
anchor = token;
start ?? (start = token.offset);
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
case "tag": {
if (tag)
onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
tag = token;
start ?? (start = token.offset);
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
}
case indicator:
if (anchor || tag)
onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
if (found)
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
found = token;
atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
hasSpace = false;
break;
case "comma":
if (flow) {
if (comma)
onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
comma = token;
atNewline = false;
hasSpace = false;
break;
}
// else fallthrough
default:
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
atNewline = false;
hasSpace = false;
}
}
const last = tokens[tokens.length - 1];
const end = last ? last.offset + last.source.length : offset;
if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
}
if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
return {
comma,
found,
spaceBefore,
comment,
hasNewline,
anchor,
tag,
newlineAfterProp,
end,
start: start ?? end
};
}
exports.resolveProps = resolveProps;
}
});
// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS({
"node_modules/yaml/dist/compose/util-contains-newline.js"(exports) {
"use strict";
function containsNewline(key) {
if (!key)
return null;
switch (key.type) {
case "alias":
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
if (key.source.includes("\n"))
return true;
if (key.end) {
for (const st of key.end)
if (st.type === "newline")
return true;
}
return false;
case "flow-collection":
for (const it of key.items) {
for (const st of it.start)
if (st.type === "newline")
return true;
if (it.sep) {
for (const st of it.sep)
if (st.type === "newline")
return true;
}
if (containsNewline(it.key) || containsNewline(it.value))
return true;
}
return false;
default:
return true;
}
}
exports.containsNewline = containsNewline;
}
});
// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS({
"node_modules/yaml/dist/compose/util-flow-indent-check.js"(exports) {
"use strict";
var utilContainsNewline = require_util_contains_newline();
function flowIndentCheck(indent, fc, onError) {
if (fc?.type === "flow-collection") {
const end = fc.end[0];
if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
const msg = "Flow end indicator should be more indented than parent";
onError(end, "BAD_INDENT", msg, true);
}
}
}
exports.flowIndentCheck = flowIndentCheck;
}
});
// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS({
"node_modules/yaml/dist/compose/util-map-includes.js"(exports) {
"use strict";
var identity = require_identity();
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
if (uniqueKeys === false)
return false;
const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value;
return items.some((pair) => isEqual(pair.key, search));
}
exports.mapIncludes = mapIncludes;
}
});
// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS({
"node_modules/yaml/dist/compose/resolve-block-map.js"(exports) {
"use strict";
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var resolveProps = require_resolve_props();
var utilContainsNewline = require_util_contains_newline();
var utilFlowIndentCheck = require_util_flow_indent_check();
var utilMapIncludes = require_util_map_includes();
var startColMsg = "All mapping items must start at the same column";
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
const map = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;
let commentEnd = null;
for (const collItem of bm.items) {
const { start, key, sep: sep4, value } = collItem;
const keyProps = resolveProps.resolveProps(start, {
indicator: "explicit-key-ind",
next: key ?? sep4?.[0],
offset,
onError,
parentIndent: bm.indent,
startOnNewline: true
});
const implicitKey = !keyProps.found;
if (implicitKey) {
if (key) {
if (key.type === "block-seq")
onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
else if ("indent" in key && key.indent !== bm.indent)
onError(offset, "BAD_INDENT", startColMsg);
}
if (!keyProps.anchor && !keyProps.tag && !sep4) {
commentEnd = keyProps.end;
if (keyProps.comment) {
if (map.comment)
map.comment += "\n" + keyProps.comment;
else
map.comment = keyProps.comment;
}
continue;
}
if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
}
} else if (keyProps.found?.indent !== bm.indent) {
onError(offset, "BAD_INDENT", startColMsg);
}
ctx.atKey = true;
const keyStart = keyProps.end;
const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
ctx.atKey = false;
if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
const valueProps = resolveProps.resolveProps(sep4 ?? [], {
indicator: "map-value-ind",
next: value,
offset: keyNode.range[2],
onError,
parentIndent: bm.indent,
startOnNewline: !key || key.type === "block-scalar"
});
offset = valueProps.end;
if (valueProps.found) {
if (implicitKey) {
if (value?.type === "block-map" && !valueProps.hasNewline)
onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
}
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep4, null, valueProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
offset = valueNode.range[2];
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map.items.push(pair);
} else {
if (implicitKey)
onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += "\n" + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map.items.push(pair);
}
}
if (commentEnd && commentEnd < offset)
onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
map.range = [bm.offset, offset, commentEnd ?? offset];
return map;
}
exports.resolveBlockMap = resolveBlockMap;
}
});
// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS({
"node_modules/yaml/dist/compose/resolve-block-seq.js"(exports) {
"use strict";
var YAMLSeq = require_YAMLSeq();
var resolveProps = require_resolve_props();
var utilFlowIndentCheck = require_util_flow_indent_check();
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
const seq = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
if (ctx.atKey)
ctx.atKey = false;
let offset = bs.offset;
let commentEnd = null;
for (const { start, value } of bs.items) {
const props = resolveProps.resolveProps(start, {
indicator: "seq-item-ind",
next: value,
offset,
onError,
parentIndent: bs.indent,
startOnNewline: true
});
if (!props.found) {
if (props.anchor || props.tag || value) {
if (value?.type === "block-seq")
onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
else
onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
} else {
commentEnd = props.end;
if (props.comment)
seq.comment = props.comment;
continue;
}
}
const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
offset = node.range[2];
seq.items.push(node);
}
seq.range = [bs.offset, offset, commentEnd ?? offset];
return seq;
}
exports.resolveBlockSeq = resolveBlockSeq;
}
});
// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS({
"node_modules/yaml/dist/compose/resolve-end.js"(exports) {
"use strict";
function resolveEnd(end, offset, reqSpace, onError) {
let comment = "";
if (end) {
let hasSpace = false;
let sep4 = "";
for (const token of end) {
const { source, type } = token;
switch (type) {
case "space":
hasSpace = true;
break;
case "comment": {
if (reqSpace && !hasSpace)
onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += sep4 + cb;
sep4 = "";
break;
}
case "newline":
if (comment)
sep4 += source;
hasSpace = true;
break;
default:
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
}
offset += source.length;
}
}
return { comment, offset };
}
exports.resolveEnd = resolveEnd;
}
});
// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS({
"node_modules/yaml/dist/compose/resolve-flow-collection.js"(exports) {
"use strict";
var identity = require_identity();
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var resolveEnd = require_resolve_end();
var resolveProps = require_resolve_props();
var utilContainsNewline = require_util_contains_newline();
var utilMapIncludes = require_util_map_includes();
var blockMsg = "Block collections are not allowed within flow collections";
var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
const isMap2 = fc.start.source === "{";
const fcName = isMap2 ? "flow map" : "flow sequence";
const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
ctx.atRoot = false;
if (ctx.atKey)
ctx.atKey = false;
let offset = fc.offset + fc.start.source.length;
for (let i = 0; i < fc.items.length; ++i) {
const collItem = fc.items[i];
const { start, key, sep: sep4, value } = collItem;
const props = resolveProps.resolveProps(start, {
flow: fcName,
indicator: "explicit-key-ind",
next: key ?? sep4?.[0],
offset,
onError,
parentIndent: fc.indent,
startOnNewline: false
});
if (!props.found) {
if (!props.anchor && !props.tag && !sep4 && !value) {
if (i === 0 && props.comma)
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
else if (i < fc.items.length - 1)
onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
if (props.comment) {
if (coll.comment)
coll.comment += "\n" + props.comment;
else
coll.comment = props.comment;
}
offset = props.end;
continue;
}
if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key))
onError(
key,
// checked by containsNewline()
"MULTILINE_IMPLICIT_KEY",
"Implicit keys of flow sequence pairs need to be on a single line"
);
}
if (i === 0) {
if (props.comma)
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
} else {
if (!props.comma)
onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
if (props.comment) {
let prevItemComment = "";
loop: for (const st of start) {
switch (st.type) {
case "comma":
case "space":
break;
case "comment":
prevItemComment = st.source.substring(1);
break loop;
default:
break loop;
}
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (identity.isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += "\n" + prevItemComment;
else
prev.comment = prevItemComment;
props.comment = props.comment.substring(prevItemComment.length + 1);
}
}
}
if (!isMap2 && !sep4 && !props.found) {
const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep4, null, props, onError);
coll.items.push(valueNode);
offset = valueNode.range[2];
if (isBlock(value))
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else {
ctx.atKey = true;
const keyStart = props.end;
const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
if (isBlock(key))
onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
ctx.atKey = false;
const valueProps = resolveProps.resolveProps(sep4 ?? [], {
flow: fcName,
indicator: "map-value-ind",
next: value,
offset: keyNode.range[2],
onError,
parentIndent: fc.indent,
startOnNewline: false
});
if (valueProps.found) {
if (!isMap2 && !props.found && ctx.options.strict) {
if (sep4)
for (const st of sep4) {
if (st === valueProps.found)
break;
if (st.type === "newline") {
onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
break;
}
}
if (props.start < valueProps.found.offset - 1024)
onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
}
} else if (value) {
if ("source" in value && value.source?.[0] === ":")
onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
else
onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
}
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep4, null, valueProps, onError) : null;
if (valueNode) {
if (isBlock(value))
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += "\n" + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
if (isMap2) {
const map = coll;
if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
map.items.push(pair);
} else {
const map = new YAMLMap.YAMLMap(ctx.schema);
map.flow = true;
map.items.push(pair);
const endRange = (valueNode ?? keyNode).range;
map.range = [keyNode.range[0], endRange[1], endRange[2]];
coll.items.push(map);
}
offset = valueNode ? valueNode.range[2] : valueProps.end;
}
}
const expectedEnd = isMap2 ? "}" : "]";
const [ce, ...ee] = fc.end;
let cePos = offset;
if (ce?.source === expectedEnd)
cePos = ce.offset + ce.source.length;
else {
const name = fcName[0].toUpperCase() + fcName.substring(1);
const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
if (ce && ce.source.length !== 1)
ee.unshift(ce);
}
if (ee.length > 0) {
const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
if (end.comment) {
if (coll.comment)
coll.comment += "\n" + end.comment;
else
coll.comment = end.comment;
}
coll.range = [fc.offset, cePos, end.offset];
} else {
coll.range = [fc.offset, cePos, cePos];
}
return coll;
}
exports.resolveFlowCollection = resolveFlowCollection;
}
});
// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS({
"node_modules/yaml/dist/compose/compose-collection.js"(exports) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var resolveBlockMap = require_resolve_block_map();
var resolveBlockSeq = require_resolve_block_seq();
var resolveFlowCollection = require_resolve_flow_collection();
function resolveCollection(CN, ctx, token, onError, tagName, tag) {
const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
const Coll = coll.constructor;
if (tagName === "!" || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN, ctx, token, props, onError) {
const tagToken = props.tag;
const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
if (token.type === "block-seq") {
const { anchor, newlineAfterProp: nl } = props;
const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
if (lastProp && (!nl || nl.offset < lastProp.offset)) {
const message = "Missing newline after block sequence props";
onError(lastProp, "MISSING_CHAR", message);
}
}
const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
return resolveCollection(CN, ctx, token, onError, tagName);
}
let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt?.collection === expType) {
ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
tag = kt;
} else {
if (kt) {
onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
} else {
onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN, ctx, token, onError, tagName);
}
}
const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
const node = identity.isNode(res) ? res : new Scalar.Scalar(res);
node.range = coll.range;
node.tag = tagName;
if (tag?.format)
node.format = tag.format;
return node;
}
exports.composeCollection = composeCollection;
}
});
// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS({
"node_modules/yaml/dist/compose/resolve-block-scalar.js"(exports) {
"use strict";
var Scalar = require_Scalar();
function resolveBlockScalar(ctx, scalar, onError) {
const start = scalar.offset;
const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
if (!header)
return { value: "", type: null, comment: "", range: [start, start, start] };
const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
const lines = scalar.source ? splitLines(scalar.source) : [];
let chompStart = lines.length;
for (let i = lines.length - 1; i >= 0; --i) {
const content = lines[i][1];
if (content === "" || content === "\r")
chompStart = i;
else
break;
}
if (chompStart === 0) {
const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
let end2 = start + header.length;
if (scalar.source)
end2 += scalar.source.length;
return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
}
let trimIndent = scalar.indent + header.indent;
let offset = scalar.offset + header.length;
let contentStart = 0;
for (let i = 0; i < chompStart; ++i) {
const [indent, content] = lines[i];
if (content === "" || content === "\r") {
if (header.indent === 0 && indent.length > trimIndent)
trimIndent = indent.length;
} else {
if (indent.length < trimIndent) {
const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
onError(offset + indent.length, "MISSING_CHAR", message);
}
if (header.indent === 0)
trimIndent = indent.length;
contentStart = i;
if (trimIndent === 0 && !ctx.atRoot) {
const message = "Block scalar values in collections must be indented";
onError(offset, "BAD_INDENT", message);
}
break;
}
offset += indent.length + content.length + 1;
}
for (let i = lines.length - 1; i >= chompStart; --i) {
if (lines[i][0].length > trimIndent)
chompStart = i + 1;
}
let value = "";
let sep4 = "";
let prevMoreIndented = false;
for (let i = 0; i < contentStart; ++i)
value += lines[i][0].slice(trimIndent) + "\n";
for (let i = contentStart; i < chompStart; ++i) {
let [indent, content] = lines[i];
offset += indent.length + content.length + 1;
const crlf = content[content.length - 1] === "\r";
if (crlf)
content = content.slice(0, -1);
if (content && indent.length < trimIndent) {
const src = header.indent ? "explicit indentation indicator" : "first line";
const message = `Block scalar lines must not be less indented than their ${src}`;
onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
indent = "";
}
if (type === Scalar.Scalar.BLOCK_LITERAL) {
value += sep4 + indent.slice(trimIndent) + content;
sep4 = "\n";
} else if (indent.length > trimIndent || content[0] === " ") {
if (sep4 === " ")
sep4 = "\n";
else if (!prevMoreIndented && sep4 === "\n")
sep4 = "\n\n";
value += sep4 + indent.slice(trimIndent) + content;
sep4 = "\n";
prevMoreIndented = true;
} else if (content === "") {
if (sep4 === "\n")
value += "\n";
else
sep4 = "\n";
} else {
value += sep4 + content;
sep4 = " ";
prevMoreIndented = false;
}
}
switch (header.chomp) {
case "-":
break;
case "+":
for (let i = chompStart; i < lines.length; ++i)
value += "\n" + lines[i][0].slice(trimIndent);
if (value[value.length - 1] !== "\n")
value += "\n";
break;
default:
value += "\n";
}
const end = start + header.length + scalar.source.length;
return { value, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset, props }, strict, onError) {
if (props[0].type !== "block-scalar-header") {
onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
return null;
}
const { source } = props[0];
const mode = source[0];
let indent = 0;
let chomp = "";
let error = -1;
for (let i = 1; i < source.length; ++i) {
const ch = source[i];
if (!chomp && (ch === "-" || ch === "+"))
chomp = ch;
else {
const n = Number(ch);
if (!indent && n)
indent = n;
else if (error === -1)
error = offset + i;
}
}
if (error !== -1)
onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
let hasSpace = false;
let comment = "";
let length = source.length;
for (let i = 1; i < props.length; ++i) {
const token = props[i];
switch (token.type) {
case "space":
hasSpace = true;
// fallthrough
case "newline":
length += token.source.length;
break;
case "comment":
if (strict && !hasSpace) {
const message = "Comments must be separated from other tokens by white space characters";
onError(token, "MISSING_CHAR", message);
}
length += token.source.length;
comment = token.source.substring(1);
break;
case "error":
onError(token, "UNEXPECTED_TOKEN", token.message);
length += token.source.length;
break;
/* istanbul ignore next should not happen */
default: {
const message = `Unexpected token in block scalar header: ${token.type}`;
onError(token, "UNEXPECTED_TOKEN", message);
const ts = token.source;
if (ts && typeof ts === "string")
length += ts.length;
}
}
}
return { mode, indent, chomp, comment, length };
}
function splitLines(source) {
const split = source.split(/\n( *)/);
const first = split[0];
const m = first.match(/^( *)/);
const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
const lines = [line0];
for (let i = 1; i < split.length; i += 2)
lines.push([split[i], split[i + 1]]);
return lines;
}
exports.resolveBlockScalar = resolveBlockScalar;
}
});
// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS({
"node_modules/yaml/dist/compose/resolve-flow-scalar.js"(exports) {
"use strict";
var Scalar = require_Scalar();
var resolveEnd = require_resolve_end();
function resolveFlowScalar(scalar, strict, onError) {
const { offset, type, source, end } = scalar;
let _type;
let value;
const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
switch (type) {
case "scalar":
_type = Scalar.Scalar.PLAIN;
value = plainValue(source, _onError);
break;
case "single-quoted-scalar":
_type = Scalar.Scalar.QUOTE_SINGLE;
value = singleQuotedValue(source, _onError);
break;
case "double-quoted-scalar":
_type = Scalar.Scalar.QUOTE_DOUBLE;
value = doubleQuotedValue(source, _onError);
break;
/* istanbul ignore next should not happen */
default:
onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
return {
value: "",
type: null,
comment: "",
range: [offset, offset + source.length, offset + source.length]
};
}
const valueEnd = offset + source.length;
const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
return {
value,
type: _type,
comment: re.comment,
range: [offset, valueEnd, re.offset]
};
}
function plainValue(source, onError) {
let badChar = "";
switch (source[0]) {
/* istanbul ignore next should not happen */
case " ":
badChar = "a tab character";
break;
case ",":
badChar = "flow indicator character ,";
break;
case "%":
badChar = "directive indicator character %";
break;
case "|":
case ">": {
badChar = `block scalar indicator ${source[0]}`;
break;
}
case "@":
case "`": {
badChar = `reserved character ${source[0]}`;
break;
}
}
if (badChar)
onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
return unfoldLines(source);
}
function singleQuotedValue(source, onError) {
if (source[source.length - 1] !== "'" || source.length === 1)
onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
return unfoldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function unfoldLines(source) {
const line = /(.*?)\r?\n/sy;
let match = line.exec(source);
if (!match)
return source;
let trimEnd, trimBoth;
try {
trimEnd = new RegExp("(?<![ ])[ ]+$");
trimBoth = new RegExp("^[ ]+|(?<![ ])[ ]+$", "g");
} catch {
trimEnd = /[ \t]+$/;
trimBoth = /^[ \t]+|[ \t]+$/g;
}
let res = match[1].replace(trimEnd, "");
let sep4 = " ";
let pos = line.lastIndex;
while (match = line.exec(source)) {
const lm = match[1].replace(trimBoth, "");
if (lm === "") {
if (sep4 === "\n")
res += sep4;
else
sep4 = "\n";
} else {
res += sep4 + lm;
sep4 = " ";
}
pos = line.lastIndex;
}
const last = /[ \t]*(.*)/sy;
last.lastIndex = pos;
match = last.exec(source);
return res + sep4 + (match?.[1] ?? "");
}
function doubleQuotedValue(source, onError) {
let res = "";
for (let i = 1; i < source.length - 1; ++i) {
const ch = source[i];
if (ch === "\r" && source[i + 1] === "\n")
continue;
if (ch === "\n") {
const { fold, offset } = foldNewline(source, i);
res += fold;
i = offset;
} else if (ch === "\\") {
let next = source[++i];
const cc = escapeCodes[next];
if (cc)
res += cc;
else if (next === "\n") {
next = source[i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
} else if (next === "\r" && source[i + 1] === "\n") {
next = source[++i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
} else if (next === "x" || next === "u" || next === "U") {
const length = next === "x" ? 2 : next === "u" ? 4 : 8;
res += parseCharCode(source, i + 1, length, onError);
i += length;
} else {
const raw = source.substr(i - 1, 2);
onError(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
res += raw;
}
} else if (ch === " " || ch === " ") {
const wsStart = i;
let next = source[i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
if (next !== "\n" && !(next === "\r" && source[i + 2] === "\n"))
res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
} else {
res += ch;
}
}
if (source[source.length - 1] !== '"' || source.length === 1)
onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
return res;
}
function foldNewline(source, offset) {
let fold = "";
let ch = source[offset + 1];
while (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
if (ch === "\r" && source[offset + 2] !== "\n")
break;
if (ch === "\n")
fold += "\n";
offset += 1;
ch = source[offset + 1];
}
if (!fold)
fold = " ";
return { fold, offset };
}
var escapeCodes = {
"0": "\0",
// null character
a: "\x07",
// bell character
b: "\b",
// backspace
e: "\x1B",
// escape character
f: "\f",
// form feed
n: "\n",
// line feed
r: "\r",
// carriage return
t: " ",
// horizontal tab
v: "\v",
// vertical tab
N: "\x85",
// Unicode next line
_: "\xA0",
// Unicode non-breaking space
L: "\u2028",
// Unicode line separator
P: "\u2029",
// Unicode paragraph separator
" ": " ",
'"': '"',
"/": "/",
"\\": "\\",
" ": " "
};
function parseCharCode(source, offset, length, onError) {
const cc = source.substr(offset, length);
const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
const code = ok ? parseInt(cc, 16) : NaN;
try {
return String.fromCodePoint(code);
} catch {
const raw = source.substr(offset - 2, length + 2);
onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
return raw;
}
}
exports.resolveFlowScalar = resolveFlowScalar;
}
});
// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS({
"node_modules/yaml/dist/compose/compose-scalar.js"(exports) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var resolveBlockScalar = require_resolve_block_scalar();
var resolveFlowScalar = require_resolve_flow_scalar();
function composeScalar(ctx, token, tagToken, onError) {
const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
let tag;
if (ctx.options.stringKeys && ctx.atKey) {
tag = ctx.schema[identity.SCALAR];
} else if (tagName)
tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
else if (token.type === "scalar")
tag = findScalarTagByTest(ctx, value, token, onError);
else
tag = ctx.schema[identity.SCALAR];
let scalar;
try {
const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
scalar = new Scalar.Scalar(value);
}
scalar.range = range;
scalar.source = value;
if (type)
scalar.type = type;
if (tagName)
scalar.tag = tagName;
if (tag.format)
scalar.format = tag.format;
if (comment)
scalar.comment = comment;
return scalar;
}
function findScalarTagByName(schema, value, tagName, tagToken, onError) {
if (tagName === "!")
return schema[identity.SCALAR];
const matchWithTest = [];
for (const tag of schema.tags) {
if (!tag.collection && tag.tag === tagName) {
if (tag.default && tag.test)
matchWithTest.push(tag);
else
return tag;
}
}
for (const tag of matchWithTest)
if (tag.test?.test(value))
return tag;
const kt = schema.knownTags[tagName];
if (kt && !kt.collection) {
schema.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
return kt;
}
onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
return schema[identity.SCALAR];
}
function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR];
if (schema.compat) {
const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR];
if (tag.tag !== compat.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat.tag);
const msg = `Value may be parsed as either ${ts} or ${cs}`;
onError(token, "TAG_RESOLVE_FAILED", msg, true);
}
}
return tag;
}
exports.composeScalar = composeScalar;
}
});
// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS({
"node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports) {
"use strict";
function emptyScalarPosition(offset, before, pos) {
if (before) {
pos ?? (pos = before.length);
for (let i = pos - 1; i >= 0; --i) {
let st = before[i];
switch (st.type) {
case "space":
case "comment":
case "newline":
offset -= st.source.length;
continue;
}
st = before[++i];
while (st?.type === "space") {
offset += st.source.length;
st = before[++i];
}
break;
}
}
return offset;
}
exports.emptyScalarPosition = emptyScalarPosition;
}
});
// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS({
"node_modules/yaml/dist/compose/compose-node.js"(exports) {
"use strict";
var Alias = require_Alias();
var identity = require_identity();
var composeCollection = require_compose_collection();
var composeScalar = require_compose_scalar();
var resolveEnd = require_resolve_end();
var utilEmptyScalarPosition = require_util_empty_scalar_position();
var CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError) {
const atKey = ctx.atKey;
const { spaceBefore, comment, anchor, tag } = props;
let node;
let isSrcToken = true;
switch (token.type) {
case "alias":
node = composeAlias(ctx, token, onError);
if (anchor || tag)
onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
break;
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "block-scalar":
node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
break;
case "block-map":
case "block-seq":
case "flow-collection":
try {
node = composeCollection.composeCollection(CN, ctx, token, props, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
onError(token, "RESOURCE_EXHAUSTION", message);
}
break;
default: {
const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
onError(token, "UNEXPECTED_TOKEN", message);
isSrcToken = false;
}
}
node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError));
if (anchor && node.anchor === "")
onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
const msg = "With stringKeys, all keys must be strings";
onError(tag ?? token, "NON_STRING_KEY", msg);
}
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
if (token.type === "scalar" && token.source === "")
node.comment = comment;
else
node.commentBefore = comment;
}
if (ctx.options.keepSourceTokens && isSrcToken)
node.srcToken = token;
return node;
}
function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
const token = {
type: "scalar",
offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
indent: -1,
source: ""
};
const node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor) {
node.anchor = anchor.source.substring(1);
if (node.anchor === "")
onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
}
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
node.comment = comment;
node.range[2] = end;
}
return node;
}
function composeAlias({ options }, { offset, source, end }, onError) {
const alias = new Alias.Alias(source.substring(1));
if (alias.source === "")
onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
if (alias.source.endsWith(":"))
onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
const valueEnd = offset + source.length;
const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
alias.range = [offset, valueEnd, re.offset];
if (re.comment)
alias.comment = re.comment;
return alias;
}
exports.composeEmptyNode = composeEmptyNode;
exports.composeNode = composeNode;
}
});
// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS({
"node_modules/yaml/dist/compose/compose-doc.js"(exports) {
"use strict";
var Document = require_Document();
var composeNode = require_compose_node();
var resolveEnd = require_resolve_end();
var resolveProps = require_resolve_props();
function composeDoc(options, directives, { offset, start, value, end }, onError) {
const opts = Object.assign({ _directives: directives }, options);
const doc = new Document.Document(void 0, opts);
const ctx = {
atKey: false,
atRoot: true,
directives: doc.directives,
options: doc.options,
schema: doc.schema
};
const props = resolveProps.resolveProps(start, {
indicator: "doc-start",
next: value ?? end?.[0],
offset,
onError,
parentIndent: 0,
startOnNewline: true
});
if (props.found) {
doc.directives.docStart = true;
if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
}
doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
const contentEnd = doc.contents.range[2];
const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
if (re.comment)
doc.comment = re.comment;
doc.range = [offset, contentEnd, re.offset];
return doc;
}
exports.composeDoc = composeDoc;
}
});
// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS({
"node_modules/yaml/dist/compose/composer.js"(exports) {
"use strict";
var node_process = __require("process");
var directives = require_directives();
var Document = require_Document();
var errors = require_errors2();
var identity = require_identity();
var composeDoc = require_compose_doc();
var resolveEnd = require_resolve_end();
function getErrorPos(src) {
if (typeof src === "number")
return [src, src + 1];
if (Array.isArray(src))
return src.length === 2 ? src : [src[0], src[1]];
const { offset, source } = src;
return [offset, offset + (typeof source === "string" ? source.length : 1)];
}
function parsePrelude(prelude) {
let comment = "";
let atComment = false;
let afterEmptyLine = false;
for (let i = 0; i < prelude.length; ++i) {
const source = prelude[i];
switch (source[0]) {
case "#":
comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
atComment = true;
afterEmptyLine = false;
break;
case "%":
if (prelude[i + 1]?.[0] !== "#")
i += 1;
atComment = false;
break;
default:
if (!atComment)
afterEmptyLine = true;
atComment = false;
}
}
return { comment, afterEmptyLine };
}
var Composer = class {
constructor(options = {}) {
this.doc = null;
this.atDirectives = false;
this.prelude = [];
this.errors = [];
this.warnings = [];
this.onError = (source, code, message, warning) => {
const pos = getErrorPos(source);
if (warning)
this.warnings.push(new errors.YAMLWarning(pos, code, message));
else
this.errors.push(new errors.YAMLParseError(pos, code, message));
};
this.directives = new directives.Directives({ version: options.version || "1.2" });
this.options = options;
}
decorate(doc, afterDoc) {
const { comment, afterEmptyLine } = parsePrelude(this.prelude);
if (comment) {
const dc = doc.contents;
if (afterDoc) {
doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
} else if (afterEmptyLine || doc.directives.docStart || !dc) {
doc.commentBefore = comment;
} else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (identity.isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}
${cb}` : comment;
} else {
const cb = dc.commentBefore;
dc.commentBefore = cb ? `${comment}
${cb}` : comment;
}
}
if (afterDoc) {
for (let i = 0; i < this.errors.length; ++i)
doc.errors.push(this.errors[i]);
for (let i = 0; i < this.warnings.length; ++i)
doc.warnings.push(this.warnings[i]);
} else {
doc.errors = this.errors;
doc.warnings = this.warnings;
}
this.prelude = [];
this.errors = [];
this.warnings = [];
}
/**
* Current stream status information.
*
* Mostly useful at the end of input for an empty stream.
*/
streamInfo() {
return {
comment: parsePrelude(this.prelude).comment,
directives: this.directives,
errors: this.errors,
warnings: this.warnings
};
}
/**
* Compose tokens into documents.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*compose(tokens, forceDoc = false, endOffset = -1) {
for (const token of tokens)
yield* this.next(token);
yield* this.end(forceDoc, endOffset);
}
/** Advance the composer by one CST token. */
*next(token) {
if (node_process.env.LOG_STREAM)
console.dir(token, { depth: null });
switch (token.type) {
case "directive":
this.directives.add(token.source, (offset, message, warning) => {
const pos = getErrorPos(token);
pos[0] += offset;
this.onError(pos, "BAD_DIRECTIVE", message, warning);
});
this.prelude.push(token.source);
this.atDirectives = true;
break;
case "document": {
const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
if (this.atDirectives && !doc.directives.docStart)
this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
this.decorate(doc, false);
if (this.doc)
yield this.doc;
this.doc = doc;
this.atDirectives = false;
break;
}
case "byte-order-mark":
case "space":
break;
case "comment":
case "newline":
this.prelude.push(token.source);
break;
case "error": {
const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
if (this.atDirectives || !this.doc)
this.errors.push(error);
else
this.doc.errors.push(error);
break;
}
case "doc-end": {
if (!this.doc) {
const msg = "Unexpected doc-end without preceding document";
this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
break;
}
this.doc.directives.docEnd = true;
const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
this.decorate(this.doc, true);
if (end.comment) {
const dc = this.doc.comment;
this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
}
this.doc.range[2] = end.offset;
break;
}
default:
this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
}
}
/**
* Call at end of input to yield any remaining document.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*end(forceDoc = false, endOffset = -1) {
if (this.doc) {
this.decorate(this.doc, true);
yield this.doc;
this.doc = null;
} else if (forceDoc) {
const opts = Object.assign({ _directives: this.directives }, this.options);
const doc = new Document.Document(void 0, opts);
if (this.atDirectives)
this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
doc.range = [0, endOffset, endOffset];
this.decorate(doc, false);
yield doc;
}
}
};
exports.Composer = Composer;
}
});
// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS({
"node_modules/yaml/dist/parse/cst-scalar.js"(exports) {
"use strict";
var resolveBlockScalar = require_resolve_block_scalar();
var resolveFlowScalar = require_resolve_flow_scalar();
var errors = require_errors2();
var stringifyString = require_stringifyString();
function resolveAsScalar(token, strict = true, onError) {
if (token) {
const _onError = (pos, code, message) => {
const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
if (onError)
onError(offset, code, message);
else
throw new errors.YAMLParseError([offset, offset + 1], code, message);
};
switch (token.type) {
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
case "block-scalar":
return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
}
}
return null;
}
function createScalarToken(value, context) {
const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context;
const source = stringifyString.stringifyString({ type, value }, {
implicitKey,
indent: indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
const end = context.end ?? [
{ type: "newline", offset: -1, indent, source: "\n" }
];
switch (source[0]) {
case "|":
case ">": {
const he = source.indexOf("\n");
const head = source.substring(0, he);
const body = source.substring(he + 1) + "\n";
const props = [
{ type: "block-scalar-header", offset, indent, source: head }
];
if (!addEndtoBlockProps(props, end))
props.push({ type: "newline", offset: -1, indent, source: "\n" });
return { type: "block-scalar", offset, indent, props, source: body };
}
case '"':
return { type: "double-quoted-scalar", offset, indent, source, end };
case "'":
return { type: "single-quoted-scalar", offset, indent, source, end };
default:
return { type: "scalar", offset, indent, source, end };
}
}
function setScalarValue(token, value, context = {}) {
let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
let indent = "indent" in token ? token.indent : null;
if (afterKey && typeof indent === "number")
indent += 2;
if (!type)
switch (token.type) {
case "single-quoted-scalar":
type = "QUOTE_SINGLE";
break;
case "double-quoted-scalar":
type = "QUOTE_DOUBLE";
break;
case "block-scalar": {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
break;
}
default:
type = "PLAIN";
}
const source = stringifyString.stringifyString({ type, value }, {
implicitKey: implicitKey || indent === null,
indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
switch (source[0]) {
case "|":
case ">":
setBlockScalarValue(token, source);
break;
case '"':
setFlowScalarValue(token, source, "double-quoted-scalar");
break;
case "'":
setFlowScalarValue(token, source, "single-quoted-scalar");
break;
default:
setFlowScalarValue(token, source, "scalar");
}
}
function setBlockScalarValue(token, source) {
const he = source.indexOf("\n");
const head = source.substring(0, he);
const body = source.substring(he + 1) + "\n";
if (token.type === "block-scalar") {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
header.source = head;
token.source = body;
} else {
const { offset } = token;
const indent = "indent" in token ? token.indent : -1;
const props = [
{ type: "block-scalar-header", offset, indent, source: head }
];
if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0))
props.push({ type: "newline", offset: -1, indent, source: "\n" });
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type: "block-scalar", indent, props, source: body });
}
}
function addEndtoBlockProps(props, end) {
if (end)
for (const st of end)
switch (st.type) {
case "space":
case "comment":
props.push(st);
break;
case "newline":
props.push(st);
return true;
}
return false;
}
function setFlowScalarValue(token, source, type) {
switch (token.type) {
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
token.type = type;
token.source = source;
break;
case "block-scalar": {
const end = token.props.slice(1);
let oa = source.length;
if (token.props[0].type === "block-scalar-header")
oa -= token.props[0].source.length;
for (const tok of end)
tok.offset += oa;
delete token.props;
Object.assign(token, { type, source, end });
break;
}
case "block-map":
case "block-seq": {
const offset = token.offset + source.length;
const nl = { type: "newline", offset, indent: token.indent, source: "\n" };
delete token.items;
Object.assign(token, { type, source, end: [nl] });
break;
}
default: {
const indent = "indent" in token ? token.indent : -1;
const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type, indent, source, end });
}
}
}
exports.createScalarToken = createScalarToken;
exports.resolveAsScalar = resolveAsScalar;
exports.setScalarValue = setScalarValue;
}
});
// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS({
"node_modules/yaml/dist/parse/cst-stringify.js"(exports) {
"use strict";
var stringify7 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst);
function stringifyToken(token) {
switch (token.type) {
case "block-scalar": {
let res = "";
for (const tok of token.props)
res += stringifyToken(tok);
return res + token.source;
}
case "block-map":
case "block-seq": {
let res = "";
for (const item of token.items)
res += stringifyItem(item);
return res;
}
case "flow-collection": {
let res = token.start.source;
for (const item of token.items)
res += stringifyItem(item);
for (const st of token.end)
res += st.source;
return res;
}
case "document": {
let res = stringifyItem(token);
if (token.end)
for (const st of token.end)
res += st.source;
return res;
}
default: {
let res = token.source;
if ("end" in token && token.end)
for (const st of token.end)
res += st.source;
return res;
}
}
}
function stringifyItem({ start, key, sep: sep4, value }) {
let res = "";
for (const st of start)
res += st.source;
if (key)
res += stringifyToken(key);
if (sep4)
for (const st of sep4)
res += st.source;
if (value)
res += stringifyToken(value);
return res;
}
exports.stringify = stringify7;
}
});
// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS({
"node_modules/yaml/dist/parse/cst-visit.js"(exports) {
"use strict";
var BREAK = /* @__PURE__ */ Symbol("break visit");
var SKIP = /* @__PURE__ */ Symbol("skip children");
var REMOVE = /* @__PURE__ */ Symbol("remove item");
function visit2(cst, visitor) {
if ("type" in cst && cst.type === "document")
cst = { start: cst.start, value: cst.value };
_visit(Object.freeze([]), cst, visitor);
}
visit2.BREAK = BREAK;
visit2.SKIP = SKIP;
visit2.REMOVE = REMOVE;
visit2.itemAtPath = (cst, path) => {
let item = cst;
for (const [field, index] of path) {
const tok = item?.[field];
if (tok && "items" in tok) {
item = tok.items[index];
} else
return void 0;
}
return item;
};
visit2.parentCollection = (cst, path) => {
const parent = visit2.itemAtPath(cst, path.slice(0, -1));
const field = path[path.length - 1][0];
const coll = parent?.[field];
if (coll && "items" in coll)
return coll;
throw new Error("Parent collection not found");
};
function _visit(path, item, visitor) {
let ctrl = visitor(item, path);
if (typeof ctrl === "symbol")
return ctrl;
for (const field of ["key", "value"]) {
const token = item[field];
if (token && "items" in token) {
for (let i = 0; i < token.items.length; ++i) {
const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
token.items.splice(i, 1);
i -= 1;
}
}
if (typeof ctrl === "function" && field === "key")
ctrl = ctrl(item, path);
}
}
return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
}
exports.visit = visit2;
}
});
// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS({
"node_modules/yaml/dist/parse/cst.js"(exports) {
"use strict";
var cstScalar = require_cst_scalar();
var cstStringify = require_cst_stringify();
var cstVisit = require_cst_visit();
var BOM = "\uFEFF";
var DOCUMENT = "";
var FLOW_END = "";
var SCALAR = "";
var isCollection2 = (token) => !!token && "items" in token;
var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
function prettyToken(token) {
switch (token) {
case BOM:
return "<BOM>";
case DOCUMENT:
return "<DOC>";
case FLOW_END:
return "<FLOW_END>";
case SCALAR:
return "<SCALAR>";
default:
return JSON.stringify(token);
}
}
function tokenType(source) {
switch (source) {
case BOM:
return "byte-order-mark";
case DOCUMENT:
return "doc-mode";
case FLOW_END:
return "flow-error-end";
case SCALAR:
return "scalar";
case "---":
return "doc-start";
case "...":
return "doc-end";
case "":
case "\n":
case "\r\n":
return "newline";
case "-":
return "seq-item-ind";
case "?":
return "explicit-key-ind";
case ":":
return "map-value-ind";
case "{":
return "flow-map-start";
case "}":
return "flow-map-end";
case "[":
return "flow-seq-start";
case "]":
return "flow-seq-end";
case ",":
return "comma";
}
switch (source[0]) {
case " ":
case " ":
return "space";
case "#":
return "comment";
case "%":
return "directive-line";
case "*":
return "alias";
case "&":
return "anchor";
case "!":
return "tag";
case "'":
return "single-quoted-scalar";
case '"':
return "double-quoted-scalar";
case "|":
case ">":
return "block-scalar-header";
}
return null;
}
exports.createScalarToken = cstScalar.createScalarToken;
exports.resolveAsScalar = cstScalar.resolveAsScalar;
exports.setScalarValue = cstScalar.setScalarValue;
exports.stringify = cstStringify.stringify;
exports.visit = cstVisit.visit;
exports.BOM = BOM;
exports.DOCUMENT = DOCUMENT;
exports.FLOW_END = FLOW_END;
exports.SCALAR = SCALAR;
exports.isCollection = isCollection2;
exports.isScalar = isScalar2;
exports.prettyToken = prettyToken;
exports.tokenType = tokenType;
}
});
// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS({
"node_modules/yaml/dist/parse/lexer.js"(exports) {
"use strict";
var cst = require_cst();
function isEmpty(ch) {
switch (ch) {
case void 0:
case " ":
case "\n":
case "\r":
case " ":
return true;
default:
return false;
}
}
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r ");
var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
var Lexer = class {
constructor() {
this.atEnd = false;
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
this.buffer = "";
this.flowKey = false;
this.flowLevel = 0;
this.indentNext = 0;
this.indentValue = 0;
this.lineEndPos = null;
this.next = null;
this.pos = 0;
}
/**
* Generate YAML tokens from the `source` string. If `incomplete`,
* a part of the last line may be left as a buffer for the next call.
*
* @returns A generator of lexical tokens
*/
*lex(source, incomplete = false) {
if (source) {
if (typeof source !== "string")
throw TypeError("source is not a string");
this.buffer = this.buffer ? this.buffer + source : source;
this.lineEndPos = null;
}
this.atEnd = !incomplete;
let next = this.next ?? "stream";
while (next && (incomplete || this.hasChars(1)))
next = yield* this.parseNext(next);
}
atLineEnd() {
let i = this.pos;
let ch = this.buffer[i];
while (ch === " " || ch === " ")
ch = this.buffer[++i];
if (!ch || ch === "#" || ch === "\n")
return true;
if (ch === "\r")
return this.buffer[i + 1] === "\n";
return false;
}
charAt(n) {
return this.buffer[this.pos + n];
}
continueScalar(offset) {
let ch = this.buffer[offset];
if (this.indentNext > 0) {
let indent = 0;
while (ch === " ")
ch = this.buffer[++indent + offset];
if (ch === "\r") {
const next = this.buffer[indent + offset + 1];
if (next === "\n" || !next && !this.atEnd)
return offset + indent + 1;
}
return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
}
if (ch === "-" || ch === ".") {
const dt = this.buffer.substr(offset, 3);
if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
return -1;
}
return offset;
}
getLine() {
let end = this.lineEndPos;
if (typeof end !== "number" || end !== -1 && end < this.pos) {
end = this.buffer.indexOf("\n", this.pos);
this.lineEndPos = end;
}
if (end === -1)
return this.atEnd ? this.buffer.substring(this.pos) : null;
if (this.buffer[end - 1] === "\r")
end -= 1;
return this.buffer.substring(this.pos, end);
}
hasChars(n) {
return this.pos + n <= this.buffer.length;
}
setNext(state) {
this.buffer = this.buffer.substring(this.pos);
this.pos = 0;
this.lineEndPos = null;
this.next = state;
return null;
}
peek(n) {
return this.buffer.substr(this.pos, n);
}
*parseNext(next) {
switch (next) {
case "stream":
return yield* this.parseStream();
case "line-start":
return yield* this.parseLineStart();
case "block-start":
return yield* this.parseBlockStart();
case "doc":
return yield* this.parseDocument();
case "flow":
return yield* this.parseFlowCollection();
case "quoted-scalar":
return yield* this.parseQuotedScalar();
case "block-scalar":
return yield* this.parseBlockScalar();
case "plain-scalar":
return yield* this.parsePlainScalar();
}
}
*parseStream() {
let line = this.getLine();
if (line === null)
return this.setNext("stream");
if (line[0] === cst.BOM) {
yield* this.pushCount(1);
line = line.substring(1);
}
if (line[0] === "%") {
let dirEnd = line.length;
let cs = line.indexOf("#");
while (cs !== -1) {
const ch = line[cs - 1];
if (ch === " " || ch === " ") {
dirEnd = cs - 1;
break;
} else {
cs = line.indexOf("#", cs + 1);
}
}
while (true) {
const ch = line[dirEnd - 1];
if (ch === " " || ch === " ")
dirEnd -= 1;
else
break;
}
const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
yield* this.pushCount(line.length - n);
this.pushNewline();
return "stream";
}
if (this.atLineEnd()) {
const sp = yield* this.pushSpaces(true);
yield* this.pushCount(line.length - sp);
yield* this.pushNewline();
return "stream";
}
yield cst.DOCUMENT;
return yield* this.parseLineStart();
}
*parseLineStart() {
const ch = this.charAt(0);
if (!ch && !this.atEnd)
return this.setNext("line-start");
if (ch === "-" || ch === ".") {
if (!this.atEnd && !this.hasChars(4))
return this.setNext("line-start");
const s = this.peek(3);
if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
this.indentValue = 0;
this.indentNext = 0;
return s === "---" ? "doc" : "stream";
}
}
this.indentValue = yield* this.pushSpaces(false);
if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
this.indentNext = this.indentValue;
return yield* this.parseBlockStart();
}
*parseBlockStart() {
const [ch0, ch1] = this.peek(2);
if (!ch1 && !this.atEnd)
return this.setNext("block-start");
if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
this.indentNext = this.indentValue + 1;
this.indentValue += n;
return "block-start";
}
return "doc";
}
*parseDocument() {
yield* this.pushSpaces(true);
const line = this.getLine();
if (line === null)
return this.setNext("doc");
let n = yield* this.pushIndicators();
switch (line[n]) {
case "#":
yield* this.pushCount(line.length - n);
// fallthrough
case void 0:
yield* this.pushNewline();
return yield* this.parseLineStart();
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel = 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
return "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "doc";
case '"':
case "'":
return yield* this.parseQuotedScalar();
case "|":
case ">":
n += yield* this.parseBlockScalarHeader();
n += yield* this.pushSpaces(true);
yield* this.pushCount(line.length - n);
yield* this.pushNewline();
return yield* this.parseBlockScalar();
default:
return yield* this.parsePlainScalar();
}
}
*parseFlowCollection() {
let nl, sp;
let indent = -1;
do {
nl = yield* this.pushNewline();
if (nl > 0) {
sp = yield* this.pushSpaces(false);
this.indentValue = indent = sp;
} else {
sp = 0;
}
sp += yield* this.pushSpaces(true);
} while (nl + sp > 0);
const line = this.getLine();
if (line === null)
return this.setNext("flow");
if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
if (!atFlowEndMarker) {
this.flowLevel = 0;
yield cst.FLOW_END;
return yield* this.parseLineStart();
}
}
let n = 0;
while (line[n] === ",") {
n += yield* this.pushCount(1);
n += yield* this.pushSpaces(true);
this.flowKey = false;
}
n += yield* this.pushIndicators();
switch (line[n]) {
case void 0:
return "flow";
case "#":
yield* this.pushCount(line.length - n);
return "flow";
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel += 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
this.flowKey = true;
this.flowLevel -= 1;
return this.flowLevel ? "flow" : "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "flow";
case '"':
case "'":
this.flowKey = true;
return yield* this.parseQuotedScalar();
case ":": {
const next = this.charAt(1);
if (this.flowKey || isEmpty(next) || next === ",") {
this.flowKey = false;
yield* this.pushCount(1);
yield* this.pushSpaces(true);
return "flow";
}
}
// fallthrough
default:
this.flowKey = false;
return yield* this.parsePlainScalar();
}
}
*parseQuotedScalar() {
const quote = this.charAt(0);
let end = this.buffer.indexOf(quote, this.pos + 1);
if (quote === "'") {
while (end !== -1 && this.buffer[end + 1] === "'")
end = this.buffer.indexOf("'", end + 2);
} else {
while (end !== -1) {
let n = 0;
while (this.buffer[end - 1 - n] === "\\")
n += 1;
if (n % 2 === 0)
break;
end = this.buffer.indexOf('"', end + 1);
}
}
const qb = this.buffer.substring(0, end);
let nl = qb.indexOf("\n", this.pos);
if (nl !== -1) {
while (nl !== -1) {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = qb.indexOf("\n", cs);
}
if (nl !== -1) {
end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
}
}
if (end === -1) {
if (!this.atEnd)
return this.setNext("quoted-scalar");
end = this.buffer.length;
}
yield* this.pushToIndex(end + 1, false);
return this.flowLevel ? "flow" : "doc";
}
*parseBlockScalarHeader() {
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
let i = this.pos;
while (true) {
const ch = this.buffer[++i];
if (ch === "+")
this.blockScalarKeep = true;
else if (ch > "0" && ch <= "9")
this.blockScalarIndent = Number(ch) - 1;
else if (ch !== "-")
break;
}
return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
}
*parseBlockScalar() {
let nl = this.pos - 1;
let indent = 0;
let ch;
loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) {
switch (ch) {
case " ":
indent += 1;
break;
case "\n":
nl = i2;
indent = 0;
break;
case "\r": {
const next = this.buffer[i2 + 1];
if (!next && !this.atEnd)
return this.setNext("block-scalar");
if (next === "\n")
break;
}
// fallthrough
default:
break loop;
}
}
if (!ch && !this.atEnd)
return this.setNext("block-scalar");
if (indent >= this.indentNext) {
if (this.blockScalarIndent === -1)
this.indentNext = indent;
else {
this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
}
do {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = this.buffer.indexOf("\n", cs);
} while (nl !== -1);
if (nl === -1) {
if (!this.atEnd)
return this.setNext("block-scalar");
nl = this.buffer.length;
}
}
let i = nl + 1;
ch = this.buffer[i];
while (ch === " ")
ch = this.buffer[++i];
if (ch === " ") {
while (ch === " " || ch === " " || ch === "\r" || ch === "\n")
ch = this.buffer[++i];
nl = i - 1;
} else if (!this.blockScalarKeep) {
do {
let i2 = nl - 1;
let ch2 = this.buffer[i2];
if (ch2 === "\r")
ch2 = this.buffer[--i2];
const lastChar = i2;
while (ch2 === " ")
ch2 = this.buffer[--i2];
if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar)
nl = i2;
else
break;
} while (true);
}
yield cst.SCALAR;
yield* this.pushToIndex(nl + 1, true);
return yield* this.parseLineStart();
}
*parsePlainScalar() {
const inFlow = this.flowLevel > 0;
let end = this.pos - 1;
let i = this.pos - 1;
let ch;
while (ch = this.buffer[++i]) {
if (ch === ":") {
const next = this.buffer[i + 1];
if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
break;
end = i;
} else if (isEmpty(ch)) {
let next = this.buffer[i + 1];
if (ch === "\r") {
if (next === "\n") {
i += 1;
ch = "\n";
next = this.buffer[i + 1];
} else
end = i;
}
if (next === "#" || inFlow && flowIndicatorChars.has(next))
break;
if (ch === "\n") {
const cs = this.continueScalar(i + 1);
if (cs === -1)
break;
i = Math.max(i, cs - 2);
}
} else {
if (inFlow && flowIndicatorChars.has(ch))
break;
end = i;
}
}
if (!ch && !this.atEnd)
return this.setNext("plain-scalar");
yield cst.SCALAR;
yield* this.pushToIndex(end + 1, true);
return inFlow ? "flow" : "doc";
}
*pushCount(n) {
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos += n;
return n;
}
return 0;
}
*pushToIndex(i, allowEmpty) {
const s = this.buffer.slice(this.pos, i);
if (s) {
yield s;
this.pos += s.length;
return s.length;
} else if (allowEmpty)
yield "";
return 0;
}
*pushIndicators() {
let n = 0;
loop: while (true) {
switch (this.charAt(0)) {
case "!":
n += yield* this.pushTag();
n += yield* this.pushSpaces(true);
continue loop;
case "&":
n += yield* this.pushUntil(isNotAnchorChar);
n += yield* this.pushSpaces(true);
continue loop;
case "-":
// this is an error
case "?":
// this is an error outside flow collections
case ":": {
const inFlow = this.flowLevel > 0;
const ch1 = this.charAt(1);
if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
if (!inFlow)
this.indentNext = this.indentValue + 1;
else if (this.flowKey)
this.flowKey = false;
n += yield* this.pushCount(1);
n += yield* this.pushSpaces(true);
continue loop;
}
}
}
break loop;
}
return n;
}
*pushTag() {
if (this.charAt(1) === "<") {
let i = this.pos + 2;
let ch = this.buffer[i];
while (!isEmpty(ch) && ch !== ">")
ch = this.buffer[++i];
return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
} else {
let i = this.pos + 1;
let ch = this.buffer[i];
while (ch) {
if (tagChars.has(ch))
ch = this.buffer[++i];
else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
ch = this.buffer[i += 3];
} else
break;
}
return yield* this.pushToIndex(i, false);
}
}
*pushNewline() {
const ch = this.buffer[this.pos];
if (ch === "\n")
return yield* this.pushCount(1);
else if (ch === "\r" && this.charAt(1) === "\n")
return yield* this.pushCount(2);
else
return 0;
}
*pushSpaces(allowTabs) {
let i = this.pos - 1;
let ch;
do {
ch = this.buffer[++i];
} while (ch === " " || allowTabs && ch === " ");
const n = i - this.pos;
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos = i;
}
return n;
}
*pushUntil(test) {
let i = this.pos;
let ch = this.buffer[i];
while (!test(ch))
ch = this.buffer[++i];
return yield* this.pushToIndex(i, false);
}
};
exports.Lexer = Lexer;
}
});
// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS({
"node_modules/yaml/dist/parse/line-counter.js"(exports) {
"use strict";
var LineCounter = class {
constructor() {
this.lineStarts = [];
this.addNewLine = (offset) => this.lineStarts.push(offset);
this.linePos = (offset) => {
let low = 0;
let high = this.lineStarts.length;
while (low < high) {
const mid = low + high >> 1;
if (this.lineStarts[mid] < offset)
low = mid + 1;
else
high = mid;
}
if (this.lineStarts[low] === offset)
return { line: low + 1, col: 1 };
if (low === 0)
return { line: 0, col: offset };
const start = this.lineStarts[low - 1];
return { line: low, col: offset - start + 1 };
};
}
};
exports.LineCounter = LineCounter;
}
});
// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS({
"node_modules/yaml/dist/parse/parser.js"(exports) {
"use strict";
var node_process = __require("process");
var cst = require_cst();
var lexer = require_lexer();
function includesToken(list, type) {
for (let i = 0; i < list.length; ++i)
if (list[i].type === type)
return true;
return false;
}
function findNonEmptyIndex(list) {
for (let i = 0; i < list.length; ++i) {
switch (list[i].type) {
case "space":
case "comment":
case "newline":
break;
default:
return i;
}
}
return -1;
}
function isFlowToken(token) {
switch (token?.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "flow-collection":
return true;
default:
return false;
}
}
function getPrevProps(parent) {
switch (parent.type) {
case "document":
return parent.start;
case "block-map": {
const it = parent.items[parent.items.length - 1];
return it.sep ?? it.start;
}
case "block-seq":
return parent.items[parent.items.length - 1].start;
/* istanbul ignore next should not happen */
default:
return [];
}
}
function getFirstKeyStartProps(prev) {
if (prev.length === 0)
return [];
let i = prev.length;
loop: while (--i >= 0) {
switch (prev[i].type) {
case "doc-start":
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
case "newline":
break loop;
}
}
while (prev[++i]?.type === "space") {
}
return prev.splice(i, prev.length);
}
function arrayPushArray(target, source) {
if (source.length < 1e5)
Array.prototype.push.apply(target, source);
else
for (let i = 0; i < source.length; ++i)
target.push(source[i]);
}
function fixFlowSeqItems(fc) {
if (fc.start.type === "flow-seq-start") {
for (const it of fc.items) {
if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
if (it.key)
it.value = it.key;
delete it.key;
if (isFlowToken(it.value)) {
if (it.value.end)
arrayPushArray(it.value.end, it.sep);
else
it.value.end = it.sep;
} else
arrayPushArray(it.start, it.sep);
delete it.sep;
}
}
}
}
var Parser = class {
/**
* @param onNewLine - If defined, called separately with the start position of
* each new line (in `parse()`, including the start of input).
*/
constructor(onNewLine) {
this.atNewLine = true;
this.atScalar = false;
this.indent = 0;
this.offset = 0;
this.onKeyLine = false;
this.stack = [];
this.source = "";
this.type = "";
this.lexer = new lexer.Lexer();
this.onNewLine = onNewLine;
}
/**
* Parse `source` as a YAML stream.
* If `incomplete`, a part of the last line may be left as a buffer for the next call.
*
* Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
*
* @returns A generator of tokens representing each directive, document, and other structure.
*/
*parse(source, incomplete = false) {
if (this.onNewLine && this.offset === 0)
this.onNewLine(0);
for (const lexeme of this.lexer.lex(source, incomplete))
yield* this.next(lexeme);
if (!incomplete)
yield* this.end();
}
/**
* Advance the parser by the `source` of one lexical token.
*/
*next(source) {
this.source = source;
if (node_process.env.LOG_TOKENS)
console.log("|", cst.prettyToken(source));
if (this.atScalar) {
this.atScalar = false;
yield* this.step();
this.offset += source.length;
return;
}
const type = cst.tokenType(source);
if (!type) {
const message = `Not a YAML token: ${source}`;
yield* this.pop({ type: "error", offset: this.offset, message, source });
this.offset += source.length;
} else if (type === "scalar") {
this.atNewLine = false;
this.atScalar = true;
this.type = "scalar";
} else {
this.type = type;
yield* this.step();
switch (type) {
case "newline":
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine)
this.onNewLine(this.offset + source.length);
break;
case "space":
if (this.atNewLine && source[0] === " ")
this.indent += source.length;
break;
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
if (this.atNewLine)
this.indent += source.length;
break;
case "doc-mode":
case "flow-error-end":
return;
default:
this.atNewLine = false;
}
this.offset += source.length;
}
}
/** Call at end of input to push out any remaining constructions */
*end() {
while (this.stack.length > 0)
yield* this.pop();
}
get sourceToken() {
const st = {
type: this.type,
offset: this.offset,
indent: this.indent,
source: this.source
};
return st;
}
*step() {
const top = this.peek(1);
if (this.type === "doc-end" && top?.type !== "doc-end") {
while (this.stack.length > 0)
yield* this.pop();
this.stack.push({
type: "doc-end",
offset: this.offset,
source: this.source
});
return;
}
if (!top)
return yield* this.stream();
switch (top.type) {
case "document":
return yield* this.document(top);
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return yield* this.scalar(top);
case "block-scalar":
return yield* this.blockScalar(top);
case "block-map":
return yield* this.blockMap(top);
case "block-seq":
return yield* this.blockSequence(top);
case "flow-collection":
return yield* this.flowCollection(top);
case "doc-end":
return yield* this.documentEnd(top);
}
yield* this.pop();
}
peek(n) {
return this.stack[this.stack.length - n];
}
*pop(error) {
const token = error ?? this.stack.pop();
if (!token) {
const message = "Tried to pop an empty stack";
yield { type: "error", offset: this.offset, source: "", message };
} else if (this.stack.length === 0) {
yield token;
} else {
const top = this.peek(1);
if (token.type === "block-scalar") {
token.indent = "indent" in top ? top.indent : 0;
} else if (token.type === "flow-collection" && top.type === "document") {
token.indent = 0;
}
if (token.type === "flow-collection")
fixFlowSeqItems(token);
switch (top.type) {
case "document":
top.value = token;
break;
case "block-scalar":
top.props.push(token);
break;
case "block-map": {
const it = top.items[top.items.length - 1];
if (it.value) {
top.items.push({ start: [], key: token, sep: [] });
this.onKeyLine = true;
return;
} else if (it.sep) {
it.value = token;
} else {
Object.assign(it, { key: token, sep: [] });
this.onKeyLine = !it.explicitKey;
return;
}
break;
}
case "block-seq": {
const it = top.items[top.items.length - 1];
if (it.value)
top.items.push({ start: [], value: token });
else
it.value = token;
break;
}
case "flow-collection": {
const it = top.items[top.items.length - 1];
if (!it || it.value)
top.items.push({ start: [], key: token, sep: [] });
else if (it.sep)
it.value = token;
else
Object.assign(it, { key: token, sep: [] });
return;
}
/* istanbul ignore next should not happen */
default:
yield* this.pop();
yield* this.pop(token);
}
if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
const last = token.items[token.items.length - 1];
if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
if (top.type === "document")
top.end = last.start;
else
top.items.push({ start: last.start });
token.items.splice(-1, 1);
}
}
}
}
*stream() {
switch (this.type) {
case "directive-line":
yield { type: "directive", offset: this.offset, source: this.source };
return;
case "byte-order-mark":
case "space":
case "comment":
case "newline":
yield this.sourceToken;
return;
case "doc-mode":
case "doc-start": {
const doc = {
type: "document",
offset: this.offset,
start: []
};
if (this.type === "doc-start")
doc.start.push(this.sourceToken);
this.stack.push(doc);
return;
}
}
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML stream`,
source: this.source
};
}
*document(doc) {
if (doc.value)
return yield* this.lineEnd(doc);
switch (this.type) {
case "doc-start": {
if (findNonEmptyIndex(doc.start) !== -1) {
yield* this.pop();
yield* this.step();
} else
doc.start.push(this.sourceToken);
return;
}
case "anchor":
case "tag":
case "space":
case "comment":
case "newline":
doc.start.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(doc);
if (bv)
this.stack.push(bv);
else {
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML document`,
source: this.source
};
}
}
*scalar(scalar) {
if (this.type === "map-value-ind") {
const prev = getPrevProps(this.peek(2));
const start = getFirstKeyStartProps(prev);
let sep4;
if (scalar.end) {
sep4 = scalar.end;
sep4.push(this.sourceToken);
delete scalar.end;
} else
sep4 = [this.sourceToken];
const map = {
type: "block-map",
offset: scalar.offset,
indent: scalar.indent,
items: [{ start, key: scalar, sep: sep4 }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map;
} else
yield* this.lineEnd(scalar);
}
*blockScalar(scalar) {
switch (this.type) {
case "space":
case "comment":
case "newline":
scalar.props.push(this.sourceToken);
return;
case "scalar":
scalar.source = this.source;
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine) {
let nl = this.source.indexOf("\n") + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf("\n", nl) + 1;
}
}
yield* this.pop();
break;
/* istanbul ignore next should not happen */
default:
yield* this.pop();
yield* this.step();
}
}
*blockMap(map) {
const it = map.items[map.items.length - 1];
switch (this.type) {
case "newline":
this.onKeyLine = false;
if (it.value) {
const end = "end" in it.value ? it.value.end : void 0;
const last = Array.isArray(end) ? end[end.length - 1] : void 0;
if (last?.type === "comment")
end?.push(this.sourceToken);
else
map.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "space":
case "comment":
if (it.value) {
map.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
if (this.atIndentedComment(it.start, map.indent)) {
const prev = map.items[map.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
arrayPushArray(end, it.start);
end.push(this.sourceToken);
map.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
}
if (this.indent >= map.indent) {
const atMapIndent = !this.onKeyLine && this.indent === map.indent;
const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
let start = [];
if (atNextItem && it.sep && !it.value) {
const nl = [];
for (let i = 0; i < it.sep.length; ++i) {
const st = it.sep[i];
switch (st.type) {
case "newline":
nl.push(i);
break;
case "space":
break;
case "comment":
if (st.indent > map.indent)
nl.length = 0;
break;
default:
nl.length = 0;
}
}
if (nl.length >= 2)
start = it.sep.splice(nl[1]);
}
switch (this.type) {
case "anchor":
case "tag":
if (atNextItem || it.value) {
start.push(this.sourceToken);
map.items.push({ start });
this.onKeyLine = true;
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "explicit-key-ind":
if (!it.sep && !it.explicitKey) {
it.start.push(this.sourceToken);
it.explicitKey = true;
} else if (atNextItem || it.value) {
start.push(this.sourceToken);
map.items.push({ start, explicitKey: true });
} else {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken], explicitKey: true }]
});
}
this.onKeyLine = true;
return;
case "map-value-ind":
if (it.explicitKey) {
if (!it.sep) {
if (includesToken(it.start, "newline")) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else {
const start2 = getFirstKeyStartProps(it.start);
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key: null, sep: [this.sourceToken] }]
});
}
} else if (it.value) {
map.items.push({ start: [], key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
});
} else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
const start2 = getFirstKeyStartProps(it.start);
const key = it.key;
const sep4 = it.sep;
sep4.push(this.sourceToken);
delete it.key;
delete it.sep;
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key, sep: sep4 }]
});
} else if (start.length > 0) {
it.sep = it.sep.concat(start, this.sourceToken);
} else {
it.sep.push(this.sourceToken);
}
} else {
if (!it.sep) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else if (it.value || atNextItem) {
map.items.push({ start, key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
});
} else {
it.sep.push(this.sourceToken);
}
}
this.onKeyLine = true;
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs = this.flowScalar(this.type);
if (atNextItem || it.value) {
map.items.push({ start, key: fs, sep: [] });
this.onKeyLine = true;
} else if (it.sep) {
this.stack.push(fs);
} else {
Object.assign(it, { key: fs, sep: [] });
this.onKeyLine = true;
}
return;
}
default: {
const bv = this.startBlockValue(map);
if (bv) {
if (bv.type === "block-seq") {
if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) {
yield* this.pop({
type: "error",
offset: this.offset,
message: "Unexpected block-seq-ind on same line with key",
source: this.source
});
return;
}
} else if (atMapIndent) {
map.items.push({ start });
}
this.stack.push(bv);
return;
}
}
}
}
yield* this.pop();
yield* this.step();
}
*blockSequence(seq) {
const it = seq.items[seq.items.length - 1];
switch (this.type) {
case "newline":
if (it.value) {
const end = "end" in it.value ? it.value.end : void 0;
const last = Array.isArray(end) ? end[end.length - 1] : void 0;
if (last?.type === "comment")
end?.push(this.sourceToken);
else
seq.items.push({ start: [this.sourceToken] });
} else
it.start.push(this.sourceToken);
return;
case "space":
case "comment":
if (it.value)
seq.items.push({ start: [this.sourceToken] });
else {
if (this.atIndentedComment(it.start, seq.indent)) {
const prev = seq.items[seq.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
arrayPushArray(end, it.start);
end.push(this.sourceToken);
seq.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
case "anchor":
case "tag":
if (it.value || this.indent <= seq.indent)
break;
it.start.push(this.sourceToken);
return;
case "seq-item-ind":
if (this.indent !== seq.indent)
break;
if (it.value || includesToken(it.start, "seq-item-ind"))
seq.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
}
if (this.indent > seq.indent) {
const bv = this.startBlockValue(seq);
if (bv) {
this.stack.push(bv);
return;
}
}
yield* this.pop();
yield* this.step();
}
*flowCollection(fc) {
const it = fc.items[fc.items.length - 1];
if (this.type === "flow-error-end") {
let top;
do {
yield* this.pop();
top = this.peek(1);
} while (top?.type === "flow-collection");
} else if (fc.end.length === 0) {
switch (this.type) {
case "comma":
case "explicit-key-ind":
if (!it || it.sep)
fc.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
case "map-value-ind":
if (!it || it.value)
fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
Object.assign(it, { key: null, sep: [this.sourceToken] });
return;
case "space":
case "comment":
case "newline":
case "anchor":
case "tag":
if (!it || it.value)
fc.items.push({ start: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
it.start.push(this.sourceToken);
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs = this.flowScalar(this.type);
if (!it || it.value)
fc.items.push({ start: [], key: fs, sep: [] });
else if (it.sep)
this.stack.push(fs);
else
Object.assign(it, { key: fs, sep: [] });
return;
}
case "flow-map-end":
case "flow-seq-end":
fc.end.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(fc);
if (bv)
this.stack.push(bv);
else {
yield* this.pop();
yield* this.step();
}
} else {
const parent = this.peek(2);
if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
yield* this.pop();
yield* this.step();
} else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
fixFlowSeqItems(fc);
const sep4 = fc.end.splice(1, fc.end.length);
sep4.push(this.sourceToken);
const map = {
type: "block-map",
offset: fc.offset,
indent: fc.indent,
items: [{ start, key: fc, sep: sep4 }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map;
} else {
yield* this.lineEnd(fc);
}
}
}
flowScalar(type) {
if (this.onNewLine) {
let nl = this.source.indexOf("\n") + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf("\n", nl) + 1;
}
}
return {
type,
offset: this.offset,
indent: this.indent,
source: this.source
};
}
startBlockValue(parent) {
switch (this.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return this.flowScalar(this.type);
case "block-scalar-header":
return {
type: "block-scalar",
offset: this.offset,
indent: this.indent,
props: [this.sourceToken],
source: ""
};
case "flow-map-start":
case "flow-seq-start":
return {
type: "flow-collection",
offset: this.offset,
indent: this.indent,
start: this.sourceToken,
items: [],
end: []
};
case "seq-item-ind":
return {
type: "block-seq",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
};
case "explicit-key-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
start.push(this.sourceToken);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, explicitKey: true }]
};
}
case "map-value-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
};
}
}
return null;
}
atIndentedComment(start, indent) {
if (this.type !== "comment")
return false;
if (this.indent <= indent)
return false;
return start.every((st) => st.type === "newline" || st.type === "space");
}
*documentEnd(docEnd) {
if (this.type !== "doc-mode") {
if (docEnd.end)
docEnd.end.push(this.sourceToken);
else
docEnd.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
*lineEnd(token) {
switch (this.type) {
case "comma":
case "doc-start":
case "doc-end":
case "flow-seq-end":
case "flow-map-end":
case "map-value-ind":
yield* this.pop();
yield* this.step();
break;
case "newline":
this.onKeyLine = false;
// fallthrough
case "space":
case "comment":
default:
if (token.end)
token.end.push(this.sourceToken);
else
token.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
};
exports.Parser = Parser;
}
});
// node_modules/yaml/dist/public-api.js
var require_public_api = __commonJS({
"node_modules/yaml/dist/public-api.js"(exports) {
"use strict";
var composer = require_composer();
var Document = require_Document();
var errors = require_errors2();
var log = require_log();
var identity = require_identity();
var lineCounter = require_line_counter();
var parser = require_parser();
function parseOptions(options) {
const prettyErrors = options.prettyErrors !== false;
const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
return { lineCounter: lineCounter$1, prettyErrors };
}
function parseAllDocuments(source, options = {}) {
const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
const composer$1 = new composer.Composer(options);
const docs = Array.from(composer$1.compose(parser$1.parse(source)));
if (prettyErrors && lineCounter2)
for (const doc of docs) {
doc.errors.forEach(errors.prettifyError(source, lineCounter2));
doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
}
if (docs.length > 0)
return docs;
return Object.assign([], { empty: true }, composer$1.streamInfo());
}
function parseDocument3(source, options = {}) {
const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
const composer$1 = new composer.Composer(options);
let doc = null;
for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
if (!doc)
doc = _doc;
else if (doc.options.logLevel !== "silent") {
doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
break;
}
}
if (prettyErrors && lineCounter2) {
doc.errors.forEach(errors.prettifyError(source, lineCounter2));
doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
}
return doc;
}
function parse11(src, reviver, options) {
let _reviver = void 0;
if (typeof reviver === "function") {
_reviver = reviver;
} else if (options === void 0 && reviver && typeof reviver === "object") {
options = reviver;
}
const doc = parseDocument3(src, options);
if (!doc)
return null;
doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
if (doc.errors.length > 0) {
if (doc.options.logLevel !== "silent")
throw doc.errors[0];
else
doc.errors = [];
}
return doc.toJS(Object.assign({ reviver: _reviver }, options));
}
function stringify7(value, replacer, options) {
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options === void 0 && replacer) {
options = replacer;
}
if (typeof options === "string")
options = options.length;
if (typeof options === "number") {
const indent = Math.round(options);
options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
}
if (value === void 0) {
const { keepUndefined } = options ?? replacer ?? {};
if (!keepUndefined)
return void 0;
}
if (identity.isDocument(value) && !_replacer)
return value.toString(options);
return new Document.Document(value, _replacer, options).toString(options);
}
exports.parse = parse11;
exports.parseAllDocuments = parseAllDocuments;
exports.parseDocument = parseDocument3;
exports.stringify = stringify7;
}
});
// node_modules/yaml/dist/index.js
var require_dist = __commonJS({
"node_modules/yaml/dist/index.js"(exports) {
"use strict";
var composer = require_composer();
var Document = require_Document();
var Schema = require_Schema();
var errors = require_errors2();
var Alias = require_Alias();
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var cst = require_cst();
var lexer = require_lexer();
var lineCounter = require_line_counter();
var parser = require_parser();
var publicApi = require_public_api();
var visit2 = require_visit();
exports.Composer = composer.Composer;
exports.Document = Document.Document;
exports.Schema = Schema.Schema;
exports.YAMLError = errors.YAMLError;
exports.YAMLParseError = errors.YAMLParseError;
exports.YAMLWarning = errors.YAMLWarning;
exports.Alias = Alias.Alias;
exports.isAlias = identity.isAlias;
exports.isCollection = identity.isCollection;
exports.isDocument = identity.isDocument;
exports.isMap = identity.isMap;
exports.isNode = identity.isNode;
exports.isPair = identity.isPair;
exports.isScalar = identity.isScalar;
exports.isSeq = identity.isSeq;
exports.Pair = Pair.Pair;
exports.Scalar = Scalar.Scalar;
exports.YAMLMap = YAMLMap.YAMLMap;
exports.YAMLSeq = YAMLSeq.YAMLSeq;
exports.CST = cst;
exports.Lexer = lexer.Lexer;
exports.LineCounter = lineCounter.LineCounter;
exports.Parser = parser.Parser;
exports.parse = publicApi.parse;
exports.parseAllDocuments = publicApi.parseAllDocuments;
exports.parseDocument = publicApi.parseDocument;
exports.stringify = publicApi.stringify;
exports.visit = visit2.visit;
exports.visitAsync = visit2.visitAsync;
}
});
// plugins/kxm/src/runtime-service.ts
import { createHash as createHash9 } from "node:crypto";
import { existsSync as existsSync8, readdirSync as readdirSync4, readFileSync as readFileSync5 } from "node:fs";
import { join as join8 } from "node:path";
// plugins/kxm/src/project-config.ts
var import__ = __toESM(require__(), 1);
import { spawnSync as spawnSync2 } from "node:child_process";
import { createHash as createHash3 } from "node:crypto";
import { existsSync as existsSync4, lstatSync, readFileSync as readFileSync2, readdirSync as readdirSync2, realpathSync } from "node:fs";
import { basename, dirname as dirname2, extname, isAbsolute, join as join3, relative, resolve, sep } from "node:path";
// plugins/kxm/src/restricted-yaml.mjs
var import_yaml = __toESM(require_dist(), 1);
var KXM_YAML_LIMITS = Object.freeze({
maxDocumentBytes: 256 * 1024,
maxDepth: 32,
maxScalarBytes: 64 * 1024,
maxCollectionItems: 4096,
maxTotalNodes: 16384,
maxKeys: 8192
});
var ALLOWED_YAML_TAGS = /* @__PURE__ */ new Set([
"tag:yaml.org,2002:map",
"tag:yaml.org,2002:seq",
"tag:yaml.org,2002:str",
"tag:yaml.org,2002:null",
"tag:yaml.org,2002:bool",
"tag:yaml.org,2002:int",
"tag:yaml.org,2002:float"
]);
function compareCodeUnits(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
function sortIssues(issues) {
return [...issues].sort((left, right) => compareCodeUnits(left.file, right.file) || compareCodeUnits(left.phase, right.phase) || compareCodeUnits(left.code, right.code) || compareCodeUnits(left.message, right.message));
}
function issue(phase, code, file, message) {
return { phase, code, file, message };
}
var RestrictedYamlError = class extends Error {
/**
* @param {readonly { phase: string, code: string, file: string, message: string }[]} issues
*/
constructor(issues) {
const sorted = sortIssues(issues);
super(sorted.map((entry) => `${entry.file}: ${entry.code}: ${entry.message}`).join("\n"));
this.name = "RestrictedYamlError";
this.issues = sorted;
}
};
function fail(phase, code, file, message) {
throw new RestrictedYamlError([issue(phase, code, file, message)]);
}
function decodeUtf8(input, label) {
if (typeof input === "string") return input;
try {
return new TextDecoder("utf-8", { fatal: true }).decode(input);
} catch {
fail("parse", "invalid_utf8", label, "document is not valid UTF-8");
}
}
function isJsonObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function assertJsonValue(value, label, path = "$", seen = /* @__PURE__ */ new Set()) {
if (value === null || typeof value === "string" || typeof value === "boolean") return;
if (typeof value === "number") {
if (!Number.isFinite(value)) fail("parse", "non_json_number", label, `${path} is not a finite JSON number`);
return;
}
if (!value || typeof value !== "object") fail("parse", "non_json_value", label, `${path} is not JSON-compatible`);
if (seen.has(value)) fail("parse", "cyclic_value", label, `${path} is cyclic`);
seen.add(value);
if (Array.isArray(value)) {
for (const [index, candidate] of value.entries()) assertJsonValue(candidate, label, `${path}[${index}]`, seen);
} else {
const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null) {
fail("parse", "constructed_object", label, `${path} has a forbidden constructed type`);
}
for (const [key, candidate] of Object.entries(value)) assertJsonValue(candidate, label, `${path}.${key}`, seen);
}
seen.delete(value);
}
function parseRestrictedYaml(input, label = "<yaml>", limits = KXM_YAML_LIMITS) {
const byteLength = typeof input === "string" ? Buffer.byteLength(input, "utf8") : input.byteLength;
if (byteLength > limits.maxDocumentBytes) {
fail("parse", "document_too_large", label, `document exceeds ${limits.maxDocumentBytes} bytes`);
}
const text = decodeUtf8(input, label);
const document = (0, import_yaml.parseDocument)(text, {
customTags: [],
strict: true,
uniqueKeys: true
});
if (document.errors.length > 0) {
fail("parse", "invalid_yaml", label, document.errors.map((error) => error.message).join("; "));
}
if (document.warnings.length > 0) {
fail("parse", "yaml_warning", label, document.warnings.map((warning) => warning.message).join("; "));
}
let nodes = 0;
let keys = 0;
(0, import_yaml.visit)(document, (_key, node, path) => {
nodes += 1;
if (nodes > limits.maxTotalNodes) fail("parse", "node_limit", label, `document exceeds ${limits.maxTotalNodes} nodes`);
if (path.length > limits.maxDepth) fail("parse", "depth_limit", label, `document exceeds nesting depth ${limits.maxDepth}`);
if ((0, import_yaml.isAlias)(node)) fail("parse", "alias_forbidden", label, "aliases are forbidden");
if (node && typeof node === "object" && "anchor" in node && typeof node.anchor === "string") {
fail("parse", "anchor_forbidden", label, "anchors are forbidden");
}
if ((0, import_yaml.isCollection)(node) && node.items.length > limits.maxCollectionItems) {
fail("parse", "collection_limit", label, `collection exceeds ${limits.maxCollectionItems} items`);
}
if ((0, import_yaml.isMap)(node)) {
keys += node.items.length;
if (keys > limits.maxKeys) fail("parse", "key_limit", label, `document exceeds ${limits.maxKeys} mapping keys`);
for (const pair of node.items) {
if (!(0, import_yaml.isScalar)(pair.key) || typeof pair.key.value !== "string") {
fail("parse", "non_string_key", label, "mapping keys must be strings");
}
}
}
if ((0, import_yaml.isScalar)(node) && typeof node.value === "string" && Buffer.byteLength(node.value, "utf8") > limits.maxScalarBytes) {
fail("parse", "scalar_limit", label, `scalar exceeds ${limits.maxScalarBytes} bytes`);
}
if (node && typeof node === "object" && "tag" in node && typeof node.tag === "string" && !ALLOWED_YAML_TAGS.has(node.tag)) {
fail("parse", "tag_forbidden", label, `tag ${node.tag} is forbidden`);
}
});
const value = document.toJS({ maxAliasCount: 0 });
assertJsonValue(value, label);
if (!isJsonObject(value)) fail("parse", "root_not_object", label, "resource root must be a mapping");
return value;
}
// plugins/kxm/src/project-config.ts
import { pathToFileURL } from "node:url";
// plugins/kxm/src/policy-draft.mjs
import { createHash } from "node:crypto";
var POLICY_DRAFT_MODEL_SCHEMA = "kxm.model.v2";
var POLICY_DRAFT_ROLE_SCHEMA = "kxm.role.v2";
var POLICY_DRAFT_PURPOSES = Object.freeze([
"writer",
"planner",
"reviewer-arch",
"reviewer-cli",
"experiment"
]);
var POLICY_DRAFT_PERMISSIONS = Object.freeze(["edit", "read-only"]);
var POLICY_DRAFT_STATUSES = Object.freeze(["admitted", "candidate", "retired"]);
var IDENTIFIER = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/;
var ROUTE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
var SHA256 = /^[a-f0-9]{64}$/;
var TOKEN = /[\s\x00-\x1f]/u;
var EFFORTS = Object.freeze(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
var MODES = Object.freeze(["headless", "interactive", "either"]);
var MODEL_KEYS = Object.freeze([
"schema",
"id",
"aliases",
"harness",
"model",
"vendor",
"status",
"permissions",
"origin",
"thinking",
"tags",
"capabilities",
"priority",
"fallbacks",
"limits"
]);
var ROLE_KEYS = Object.freeze([
"schema",
"id",
"purpose",
"permission",
"description",
"extends",
"roster",
"skills",
"tools",
"produces",
"consumes",
"policy"
]);
var ORIGIN_KEYS = Object.freeze(["source", "sha256"]);
var LIMIT_KEYS = Object.freeze(["contextTokens", "outputTokens", "timeoutMs"]);
var TOOL_KEYS = Object.freeze(["preset", "allow", "deny"]);
var TEMPLATE_KEYS = Object.freeze(["template", "schema"]);
var POLICY_KEYS = Object.freeze(["vendorIndependenceRequired", "maxTransitions", "requiresGateVerification", "fallback"]);
var FALLBACK_KEYS = Object.freeze(["onError", "maxSwitches", "revert"]);
var FALLBACK_ERRORS = Object.freeze(["rate_limit", "transport", "provider_unavailable", "context_overflow"]);
var FALLBACK_REVERT = Object.freeze(["next_run", "never"]);
var ROSTER_ENTRY_KEYS = Object.freeze(["route", "effort", "mode"]);
var CRITIC_PURPOSES = Object.freeze(["reviewer-arch", "reviewer-cli"]);
function compareCodeUnits2(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
function sortIssues2(issues) {
return [...issues].sort((left, right) => compareCodeUnits2(left.file, right.file) || compareCodeUnits2(left.phase, right.phase) || compareCodeUnits2(left.code, right.code) || compareCodeUnits2(left.message, right.message));
}
function issue2(phase, code, file, message) {
return { phase, code, file, message };
}
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function own(object, key) {
return Object.hasOwn(object, key);
}
function extraKeys(value, allowed) {
return Object.keys(value).filter((key) => !allowed.includes(key));
}
function freezeDeep(value) {
if (value && typeof value === "object") {
for (const child of Object.values(value)) freezeDeep(child);
Object.freeze(value);
}
return value;
}
function cloneJson(value) {
return JSON.parse(JSON.stringify(value));
}
function sha256Bytes(input) {
const bytes = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
return createHash("sha256").update(bytes).digest("hex");
}
function canonicalVendor(value, aliases) {
if (typeof value !== "string") return "";
const lower = value.toLowerCase();
return own(aliases, lower) ? aliases[lower] : lower;
}
function identifier(value, max = 64) {
return typeof value === "string" && value.length >= 1 && value.length <= max && IDENTIFIER.test(value);
}
function routeId(value) {
return typeof value === "string" && value.length >= 1 && value.length <= 64 && ROUTE_ID.test(value);
}
function nonemptyToken(value, max = 512) {
return typeof value === "string" && value.length >= 1 && value.length <= max && !TOKEN.test(value);
}
function codePointCount(value) {
return [...value].length;
}
function sourcePath(value) {
if (!nonemptyToken(value)) return false;
if (value.startsWith("/") || value.includes("\\")) return false;
const parts = value.split("/");
return parts.length > 0 && parts.every((part) => part && part !== "." && part !== "..");
}
function uniqueStringList(value, allowed, { min = 1, max = 64 } = {}) {
if (!Array.isArray(value) || value.length < min || value.length > max) return false;
if (new Set(value).size !== value.length) return false;
return value.every((item) => allowed.includes(item));
}
function identifierList(value, { maxItems = 32, itemMax = 64 } = {}) {
if (!Array.isArray(value) || value.length > maxItems) return false;
if (new Set(value).size !== value.length) return false;
return value.every((item) => identifier(item, itemMax));
}
function parseDocument2(value, label, issues) {
if (typeof value === "string" || value instanceof Uint8Array) {
try {
return parseRestrictedYaml(value, label);
} catch (error) {
if (error instanceof RestrictedYamlError) issues.push(...error.issues);
else issues.push(issue2("parse", "invalid_yaml", label, error instanceof Error ? error.message : "invalid YAML"));
return void 0;
}
}
if (isObject(value)) return value;
issues.push(issue2("schema", "root_not_object", label, "resource root must be a mapping"));
return void 0;
}
function collectDocuments(raw, kind, issues) {
const collected = [];
const seen = /* @__PURE__ */ new Set();
if (raw === void 0) return collected;
if (Array.isArray(raw)) {
for (const [index, value] of raw.entries()) {
const label = `${kind}[${index}]`;
const document = parseDocument2(value, label, issues);
if (!document) continue;
const declared = document.id;
if (!routeId(declared) && !(kind === "roles" && identifier(declared))) {
issues.push(issue2("schema", "missing_id", label, `${kind.slice(0, -1)} identity is missing or invalid`));
continue;
}
if (seen.has(declared)) {
issues.push(issue2("schema", kind === "models" ? "duplicate_route_id" : "duplicate_role_id", label, `duplicate ${kind.slice(0, -1)} identity ${declared}`));
continue;
}
seen.add(declared);
collected.push({ id: declared, label: `${kind}/${declared}`, document });
}
return collected;
}
if (!isObject(raw)) {
issues.push(issue2("schema", "root_not_object", kind, `${kind} must be a mapping or array`));
return collected;
}
for (const id of Object.keys(raw).sort(compareCodeUnits2)) {
const label = `${kind}/${id}`;
if (kind === "models" ? !routeId(id) : !identifier(id)) {
issues.push(issue2("schema", "invalid_id", label, `invalid ${kind.slice(0, -1)} identity`));
continue;
}
if (seen.has(id)) {
issues.push(issue2("schema", kind === "models" ? "duplicate_route_id" : "duplicate_role_id", label, `duplicate ${kind.slice(0, -1)} identity ${id}`));
continue;
}
seen.add(id);
const document = parseDocument2(raw[id], label, issues);
if (!document) continue;
if (document.id !== void 0 && document.id !== id) {
issues.push(issue2("schema", "identity_mismatch", label, `declared id ${String(document.id)} does not match ${id}`));
continue;
}
collected.push({ id, label, document });
}
return collected;
}
function closedObject(value, allowed, label, issues, code = "schema_additionalProperties") {
if (!isObject(value)) {
issues.push(issue2("schema", "root_not_object", label, "value must be a mapping"));
return false;
}
const unexpected = extraKeys(value, allowed);
if (unexpected.length > 0) {
issues.push(issue2("schema", code, label, `unexpected properties: ${unexpected.join(", ")}`));
return false;
}
return true;
}
function required(value, keys, label, issues) {
for (const key of keys) {
if (!own(value, key)) issues.push(issue2("schema", "schema_required", label, `missing ${key}`));
}
}
function validateOrigin(origin, label, issues) {
if (!closedObject(origin, ORIGIN_KEYS, `${label}.origin`, issues)) return;
required(origin, ORIGIN_KEYS, `${label}.origin`, issues);
if (origin.source !== void 0 && !sourcePath(origin.source)) {
issues.push(issue2("schema", "origin_source_invalid", `${label}.origin`, "origin source must be a contained relative path"));
}
if (origin.sha256 !== void 0 && (typeof origin.sha256 !== "string" || !SHA256.test(origin.sha256))) {
issues.push(issue2("schema", "origin_hash_invalid", `${label}.origin`, "origin sha256 must be a 64-character hex digest"));
}
}
function validateModelShape(document, id, label, issues) {
if (!closedObject(document, MODEL_KEYS, label, issues)) return;
required(document, ["schema", "harness", "model", "vendor", "status", "permissions"], label, issues);
if (document.schema !== void 0 && document.schema !== POLICY_DRAFT_MODEL_SCHEMA) {
issues.push(issue2("schema", "schema_identity_mismatch", label, `expected ${POLICY_DRAFT_MODEL_SCHEMA}, received ${String(document.schema)}`));
}
if (document.id !== void 0 && document.id !== id) {
issues.push(issue2("schema", "identity_mismatch", label, `declared id ${String(document.id)} does not match ${id}`));
}
if (document.aliases !== void 0 && !identifierList(document.aliases)) {
issues.push(issue2("schema", "schema_pattern", label, "aliases must be unique identifiers"));
}
if (document.harness !== void 0 && !identifier(document.harness)) {
issues.push(issue2("schema", "schema_pattern", label, "harness must be an identifier"));
}
if (document.model !== void 0 && (typeof document.model !== "string" || codePointCount(document.model) < 1 || codePointCount(document.model) > 200)) {
issues.push(issue2("schema", "schema_pattern", label, "model must be a nonempty string"));
}
if (document.vendor !== void 0 && !nonemptyToken(document.vendor, 64)) {
issues.push(issue2("schema", "schema_pattern", label, "vendor must be a nonempty token"));
}
if (document.status !== void 0 && !POLICY_DRAFT_STATUSES.includes(document.status)) {
issues.push(issue2("schema", "unsupported_status", label, "status must be admitted, candidate, or retired"));
}
if (document.permissions !== void 0 && !uniqueStringList(document.permissions, POLICY_DRAFT_PERMISSIONS, { min: 1, max: 2 })) {
issues.push(issue2("schema", "schema_enum", label, "permissions must be unique edit and/or read-only"));
}
if (document.harness === "pi" && !own(document, "origin")) {
issues.push(issue2("schema", "schema_required", label, "Pi routes require origin source and sha256"));
}
if (own(document, "origin")) validateOrigin(document.origin, label, issues);
if (document.thinking !== void 0 && (typeof document.thinking !== "string" || document.thinking.length < 1 || document.thinking.length > 64)) {
issues.push(issue2("schema", "schema_pattern", label, "thinking must be a short string"));
}
if (document.tags !== void 0 && !identifierList(document.tags)) {
issues.push(issue2("schema", "schema_pattern", label, "tags must be unique identifiers"));
}
if (document.capabilities !== void 0 && !identifierList(document.capabilities)) {
issues.push(issue2("schema", "schema_pattern", label, "capabilities must be unique identifiers"));
}
if (document.priority !== void 0 && (!Number.isInteger(document.priority) || document.priority < -1e4 || document.priority > 1e4)) {
issues.push(issue2("schema", "schema_type", label, "priority must be an integer in range"));
}
if (document.fallbacks !== void 0) {
if (!Array.isArray(document.fallbacks) || document.fallbacks.length > 8) {
issues.push(issue2("schema", "schema_type", label, "fallbacks must be a bounded array"));
} else {
for (const [index, fallback] of document.fallbacks.entries()) {
if (!isObject(fallback)) {
issues.push(issue2("schema", "root_not_object", `${label}.fallbacks[${index}]`, "fallback must be a mapping"));
continue;
}
const keys = Object.keys(fallback);
const profile = keys.length === 1 && own(fallback, "profile") && identifier(fallback.profile);
const tag = own(fallback, "tag") && identifier(fallback.tag) && extraKeys(fallback, ["tag", "capabilities"]).length === 0 && (fallback.capabilities === void 0 || identifierList(fallback.capabilities));
const provider = own(fallback, "provider") && own(fallback, "model") && extraKeys(fallback, ["provider", "model"]).length === 0 && identifier(fallback.provider) && typeof fallback.model === "string" && codePointCount(fallback.model) >= 1 && codePointCount(fallback.model) <= 200;
if (!profile && !tag && !provider) {
issues.push(issue2("schema", "schema_oneOf", `${label}.fallbacks[${index}]`, "fallback does not match a retained v1 selector"));
}
}
}
}
if (document.limits !== void 0) {
if (!closedObject(document.limits, LIMIT_KEYS, `${label}.limits`, issues)) return;
for (const key of ["contextTokens", "outputTokens"]) {
if (document.limits[key] !== void 0 && (!Number.isInteger(document.limits[key]) || document.limits[key] < 1)) {
issues.push(issue2("schema", "schema_type", `${label}.limits`, `${key} must be a positive integer`));
}
}
if (document.limits.timeoutMs !== void 0 && (!Number.isInteger(document.limits.timeoutMs) || document.limits.timeoutMs < 0 || document.limits.timeoutMs > 31536e6)) {
issues.push(issue2("schema", "schema_type", `${label}.limits`, "timeoutMs must be a non-negative integer between 0 and 31536000000"));
}
}
}
function validateTemplateList(value, label, issues) {
if (!Array.isArray(value)) {
issues.push(issue2("schema", "schema_type", label, "must be an array"));
return;
}
for (const [index, entry] of value.entries()) {
const path = `${label}[${index}]`;
if (!closedObject(entry, TEMPLATE_KEYS, path, issues)) continue;
if (typeof entry.template !== "string" || !entry.template) {
issues.push(issue2("schema", "schema_required", path, "template is required"));
}
if (entry.schema !== void 0 && typeof entry.schema !== "string") {
issues.push(issue2("schema", "schema_type", path, "schema must be a string"));
}
}
}
function validateRoleShape(document, id, label, issues) {
if (!closedObject(document, ROLE_KEYS, label, issues)) return;
required(document, ["schema", "purpose", "permission", "description", "roster"], label, issues);
if (document.schema !== void 0 && document.schema !== POLICY_DRAFT_ROLE_SCHEMA) {
issues.push(issue2("schema", "schema_identity_mismatch", label, `expected ${POLICY_DRAFT_ROLE_SCHEMA}, received ${String(document.schema)}`));
}
if (document.id !== void 0 && document.id !== id) {
issues.push(issue2("schema", "identity_mismatch", label, `declared id ${String(document.id)} does not match ${id}`));
}
if (document.extends !== void 0 && !identifier(document.extends)) {
issues.push(issue2("schema", "schema_pattern", label, "extends must be a role identifier"));
}
if (document.purpose !== void 0 && !POLICY_DRAFT_PURPOSES.includes(document.purpose)) {
issues.push(issue2("schema", "unsupported_purpose", label, "purpose must be a runner role label"));
}
if (document.permission !== void 0 && !POLICY_DRAFT_PERMISSIONS.includes(document.permission)) {
issues.push(issue2("schema", "schema_enum", label, "permission must be edit or read-only"));
}
if (document.description !== void 0 && (typeof document.description !== "string" || document.description.length < 1 || document.description.length > 2e3)) {
issues.push(issue2("schema", "schema_type", label, "description must be a bounded string"));
}
if (document.roster !== void 0) {
if (!Array.isArray(document.roster) || document.roster.length > 32) {
issues.push(issue2("schema", "schema_type", label, "roster must be a bounded array"));
} else {
const seenRoutes = /* @__PURE__ */ new Set();
for (const [index, entry] of document.roster.entries()) {
const path = `${label}.roster[${index}]`;
if (!closedObject(entry, ROSTER_ENTRY_KEYS, path, issues)) continue;
if (!routeId(entry.route)) {
issues.push(issue2("schema", "schema_pattern", path, "roster route must be a route identity"));
continue;
}
if (seenRoutes.has(entry.route)) {
issues.push(issue2("schema", "duplicate_route_id", path, `duplicate roster route ${entry.route}`));
}
seenRoutes.add(entry.route);
if (entry.effort !== void 0 && !EFFORTS.includes(entry.effort)) {
issues.push(issue2("schema", "schema_enum", path, "effort is not a known helper effort"));
}
if (entry.mode !== void 0 && !MODES.includes(entry.mode)) {
issues.push(issue2("schema", "schema_enum", path, "mode must be headless, interactive, or either"));
}
}
}
}
if (document.skills !== void 0) {
if (!Array.isArray(document.skills) || document.skills.length > 64 || document.skills.some((item) => typeof item !== "string" || item.length < 1 || item.length > 128)) {
issues.push(issue2("schema", "schema_type", label, "skills must be bounded strings"));
}
}
if (document.tools !== void 0) {
if (!closedObject(document.tools, TOOL_KEYS, `${label}.tools`, issues)) return;
if (document.tools.preset !== void 0 && typeof document.tools.preset !== "string") {
issues.push(issue2("schema", "schema_type", `${label}.tools`, "preset must be a string"));
}
for (const key of ["allow", "deny"]) {
if (document.tools[key] !== void 0 && (!Array.isArray(document.tools[key]) || document.tools[key].some((item) => typeof item !== "string"))) {
issues.push(issue2("schema", "schema_type", `${label}.tools`, `${key} must be a string array`));
}
}
}
if (document.produces !== void 0) validateTemplateList(document.produces, `${label}.produces`, issues);
if (document.consumes !== void 0) validateTemplateList(document.consumes, `${label}.consumes`, issues);
if (document.policy !== void 0) {
if (!closedObject(document.policy, POLICY_KEYS, `${label}.policy`, issues)) return;
if (document.policy.vendorIndependenceRequired !== void 0 && typeof document.policy.vendorIndependenceRequired !== "boolean") {
issues.push(issue2("schema", "schema_type", `${label}.policy`, "vendorIndependenceRequired must be boolean"));
}
if (document.policy.requiresGateVerification !== void 0 && typeof document.policy.requiresGateVerification !== "boolean") {
issues.push(issue2("schema", "schema_type", `${label}.policy`, "requiresGateVerification must be boolean"));
}
if (document.policy.maxTransitions !== void 0 && (!Number.isInteger(document.policy.maxTransitions) || document.policy.maxTransitions < 1)) {
issues.push(issue2("schema", "schema_type", `${label}.policy`, "maxTransitions must be a positive integer"));
}
if (document.policy.fallback !== void 0) {
const fallback = document.policy.fallback;
const path = `${label}.policy.fallback`;
if (!closedObject(fallback, FALLBACK_KEYS, path, issues)) return;
if (fallback.onError !== void 0) {
if (!Array.isArray(fallback.onError) || new Set(fallback.onError).size !== fallback.onError.length || fallback.onError.some((item) => !FALLBACK_ERRORS.includes(item))) {
issues.push(issue2("schema", "schema_enum", path, "onError must be unique rate_limit, transport, provider_unavailable, or context_overflow values"));
}
}
if (fallback.maxSwitches !== void 0 && (!Number.isInteger(fallback.maxSwitches) || fallback.maxSwitches < 0)) {
issues.push(issue2("schema", "schema_type", path, "maxSwitches must be an integer >= 0"));
}
if (fallback.revert !== void 0 && !FALLBACK_REVERT.includes(fallback.revert)) {
issues.push(issue2("schema", "schema_enum", path, "revert must be next_run or never"));
}
}
}
}
function subset(values, allowed) {
return values.every((value) => allowed.includes(value));
}
function validateModelSemantics(model, label, options, evidence, issues) {
const aliases = options.vendorAliases ?? {};
const ceiling = options.ceilings[model.harness];
if (!ceiling) {
issues.push(issue2("semantic", "unsupported_harness", label, `no code-owned ceiling for harness ${String(model.harness)}`));
return;
}
const vendor = canonicalVendor(model.vendor, aliases);
if (options.piAllowedProviders.includes(vendor)) {
issues.push(issue2("semantic", "vendor_aggregator", label, "vendor must name the model vendor, not a billing aggregator"));
}
if (!subset(model.permissions, ceiling.permissions)) {
issues.push(issue2("semantic", "permission_escalation", label, "route permissions exceed the harness ceiling"));
}
if (Array.isArray(ceiling.models) && ceiling.models.length > 0 && !ceiling.models.includes(model.model)) {
issues.push(issue2("semantic", "model_not_in_ceiling", label, "exact model is not listed on the harness ceiling"));
}
if (model.harness === "pi") {
const parts = typeof model.model === "string" ? model.model.split("/") : [];
const nativeVendors = isObject(options.piNativeVendorProviders) ? options.piNativeVendorProviders : {};
const provider = parts[0];
const owned = own(nativeVendors, provider) ? canonicalVendor(nativeVendors[provider], aliases) : "";
const minParts = owned ? 2 : 3;
const maxParts = owned ? 2 : Number.POSITIVE_INFINITY;
if (parts.length < minParts || parts.length > maxParts || parts.some((part) => !part) || !options.piAllowedProviders.includes(provider) || owned && !/^gemini-[a-z0-9.-]+$/.test(parts[1])) {
issues.push(issue2("semantic", "unsupported_pi_model", label, "Pi model must use an allowlisted aggregator prefix"));
} else if (owned) {
if (owned !== vendor) {
issues.push(issue2("semantic", "pi_native_vendor_forbidden", label, "native vendor cannot use Pi"));
}
} else {
const prefix = canonicalVendor(parts[1], aliases);
if (options.nativePiBrakeProviders.includes(prefix) || options.nativePiBrakeProviders.includes(vendor)) {
issues.push(issue2("semantic", "pi_native_vendor_forbidden", label, "native vendor cannot use Pi"));
}
}
} else if (vendor !== ceiling.provider || typeof model.model === "string" && model.model.includes("/")) {
issues.push(issue2("semantic", "native_vendor_mismatch", label, "native route vendor or model does not match the harness ceiling"));
}
const origin = model.origin;
if (isObject(origin) && typeof origin.source === "string" && typeof origin.sha256 === "string") {
if (!own(evidence, origin.source)) {
issues.push(issue2("semantic", "origin_evidence_missing", label, `missing evidence bytes for ${origin.source}`));
} else if (sha256Bytes(evidence[origin.source]) !== origin.sha256) {
issues.push(issue2("semantic", "origin_hash_mismatch", label, "origin evidence hash does not match supplied bytes"));
}
}
}
function admittedRoute(model) {
return model.status === "admitted";
}
function validateRoleSemantics(role, id, label, models, options, issues) {
if (!Array.isArray(role.roster)) return;
for (const [index, entry] of role.roster.entries()) {
const path = `${label}.roster[${index}]`;
const model = models.get(entry.route);
if (!model) {
issues.push(issue2("reference", "route_unknown", path, `roster references unknown route ${entry.route}`));
continue;
}
const ceiling = options.ceilings[model.harness];
if (!ceiling) continue;
if (Array.isArray(ceiling.roles) && ceiling.roles.length > 0 && !ceiling.roles.includes(role.purpose)) {
issues.push(issue2("semantic", "purpose_ceiling_mismatch", path, `purpose ${role.purpose} is not allowed on harness ${model.harness}`));
}
if (!model.permissions.includes(role.permission)) {
issues.push(issue2("semantic", "permission_escalation", path, "role permission is not granted by the route"));
}
if (!ceiling.permissions.includes(role.permission)) {
issues.push(issue2("semantic", "permission_escalation", path, "role permission exceeds the harness ceiling"));
}
if (Array.isArray(ceiling.efforts) && ceiling.efforts.length > 0 && entry.effort !== void 0 && !ceiling.efforts.includes(entry.effort)) {
issues.push(issue2("semantic", "effort_ceiling_mismatch", path, "effort is not allowed on the harness ceiling"));
}
if (!admittedRoute(model)) {
issues.push(issue2("semantic", "route_not_admitted", path, `route ${entry.route} is ${model.status} and is not treated as admitted`));
}
if (model.harness === "pi") {
if (role.permission === "edit" && !["writer", "experiment"].includes(role.purpose)) {
issues.push(issue2("semantic", "permission_escalation", path, "Pi critic/planner cannot edit"));
}
if (role.purpose === "writer" && (model.permissions.length !== 1 || model.permissions[0] !== "edit")) {
issues.push(issue2("semantic", "permission_escalation", path, "Pi writer requires edit permission only"));
}
}
}
if (id === role.purpose && CRITIC_PURPOSES.includes(role.purpose)) {
const admitted = role.roster.map((entry) => models.get(entry.route)).filter((model) => model && admittedRoute(model));
if (admitted.length < 1) {
issues.push(issue2("semantic", "critic_route_count", label, "required critic purpose files must list at least one admitted route"));
} else if (role.permission !== "read-only" || admitted.some((model) => model.permissions.length !== 1 || model.permissions[0] !== "read-only")) {
issues.push(issue2("semantic", "permission_escalation", label, "critic purpose files must be read-only"));
}
}
}
function validateExtends(roles, issues) {
for (const [id, role] of roles) {
if (role.extends === void 0) continue;
const label = `roles/${id}`;
if (!roles.has(role.extends)) {
issues.push(issue2("reference", "role_extends_unknown", label, `extends names unknown role ${role.extends}`));
continue;
}
const seen = /* @__PURE__ */ new Set([id]);
let current = role.extends;
while (typeof current === "string" && current.length > 0) {
if (seen.has(current)) {
issues.push(issue2("semantic", "role_extends_cycle", label, `extends cycle: ${[...seen, current].join(" -> ")}`));
break;
}
seen.add(current);
current = roles.get(current)?.extends;
}
}
}
function validateCriticVendors(roles, models, options, issues) {
const aliases = options.vendorAliases ?? {};
const critics = [];
for (const purpose of CRITIC_PURPOSES) {
const role = roles.get(purpose);
if (!role || role.purpose !== purpose) continue;
const admitted = (role.roster ?? []).map((entry) => models.get(entry.route)).filter((model) => model && admittedRoute(model));
if (admitted.length >= 1) critics.push({ purpose, vendor: canonicalVendor(admitted[0].vendor, aliases) });
}
if (critics.length === 2 && critics[0].vendor === critics[1].vendor) {
issues.push(issue2("semantic", "critic_vendor_collision", "roles/reviewer-arch", "required critics must have independent vendors"));
}
const writer = roles.get("writer");
if (writer && critics.length > 0) {
for (const entry of writer.roster ?? []) {
const model = models.get(entry.route);
if (!model || !admittedRoute(model)) continue;
const vendor = canonicalVendor(model.vendor, aliases);
if (critics.some((critic) => critic.vendor === vendor)) {
issues.push(issue2("semantic", "writer_critic_vendor_collision", "roles/writer", "writer and critics must have independent vendors"));
}
}
}
}
function validatePolicyDraft(input, options) {
const issues = [];
if (!isObject(input)) {
return { ok: false, issues: [issue2("schema", "root_not_object", "<draft>", "draft input must be a mapping")] };
}
const unexpected = extraKeys(input, ["models", "roles", "evidence"]);
if (unexpected.length > 0) {
issues.push(issue2("schema", "schema_additionalProperties", "<draft>", `unexpected properties: ${unexpected.join(", ")}`));
}
if (!isObject(options) || !isObject(options.ceilings) || !Array.isArray(options.nativePiBrakeProviders) || !Array.isArray(options.piAllowedProviders)) {
issues.push(issue2("semantic", "ceilings_required", "<options>", "code-owned ceilings and vendor brakes must be supplied explicitly"));
return { ok: false, issues: sortIssues2(issues) };
}
const evidence = isObject(input.evidence) ? input.evidence : {};
if (input.evidence !== void 0 && !isObject(input.evidence)) {
issues.push(issue2("schema", "root_not_object", "evidence", "evidence must be a mapping of source path to bytes"));
}
const modelDocs = collectDocuments(input.models, "models", issues);
const roleDocs = collectDocuments(input.roles, "roles", issues);
for (const entry of modelDocs) validateModelShape(entry.document, entry.id, entry.label, issues);
for (const entry of roleDocs) validateRoleShape(entry.document, entry.id, entry.label, issues);
if (issues.length > 0) return { ok: false, issues: sortIssues2(issues) };
const models = /* @__PURE__ */ new Map();
for (const entry of modelDocs) {
validateModelSemantics(entry.document, entry.label, options, evidence, issues);
const normalized = cloneJson(entry.document);
normalized.id = entry.id;
models.set(entry.id, normalized);
}
const roles = /* @__PURE__ */ new Map();
for (const entry of roleDocs) {
validateRoleSemantics(entry.document, entry.id, entry.label, models, options, issues);
const normalized = cloneJson(entry.document);
normalized.id = entry.id;
roles.set(entry.id, normalized);
}
validateExtends(roles, issues);
validateCriticVendors(roles, models, options, issues);
if (issues.length > 0) return { ok: false, issues: sortIssues2(issues) };
const data = freezeDeep({
models: Object.fromEntries([...models.entries()].sort(([left], [right]) => compareCodeUnits2(left, right))),
roles: Object.fromEntries([...roles.entries()].sort(([left], [right]) => compareCodeUnits2(left, right)))
});
return { ok: true, data };
}
// plugins/kxm/src/workforce-names.mjs
var import_yaml2 = __toESM(require_dist(), 1);
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
var ROSTER_EFFORTS = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
var ROLE_IDS = Object.freeze([
"writer",
"planner",
"reviewer-arch",
"reviewer-cli",
"experiment"
]);
var ROUTE_RENAMES = Object.freeze([
["grok-native", "grok-grok-4-7"],
["qwen-openrouter-pi", "pi-qwen3-coder-plus-openrouter"],
["gemini-agy", "agy-gemini-3-8-flash-high"],
["fable-claude", "claude-fable"],
["sol-codex", "codex-gpt-5-6-sol"],
["grok-default", "grok-grok-4-6"],
["fable-default", "claude-fable"]
]);
var AGENT_RENAMES = Object.freeze([
["coordinator", "planner"],
["implementer", "writer"],
["critic-arch", "reviewer-arch"],
["critic-cli", "reviewer-cli"]
]);
var WORKFLOW_RENAMES = Object.freeze([
["implement-only", "writer-only"],
["review-arch-only", "reviewer-arch-only"],
["review-cli-only", "reviewer-cli-only"]
]);
var STEP_RENAMES = Object.freeze([
["implement", "writer"],
["critic-arch", "reviewer-arch"],
["review-arch", "reviewer-arch"],
["critic-cli", "reviewer-cli"],
["review-cli", "reviewer-cli"]
]);
var RENAMES = Object.freeze({
route: ROUTE_RENAMES,
agent: AGENT_RENAMES,
workflow: WORKFLOW_RENAMES,
step: STEP_RENAMES
});
var RESERVED_WORKFLOW_IDS = /* @__PURE__ */ new Set(["default", "land"]);
var warned = /* @__PURE__ */ new Set();
function noteDeprecatedId(kind, from, to) {
const key = `${kind}\0${from}\0${to}`;
if (warned.has(key)) return;
warned.add(key);
if (process.env.KXM_QUIET_ALIASES === "1") return;
console.warn(`kxm: deprecated ${kind} id '${from}' resolves to '${to}'`);
}
function resolveRenamedId(requested, knownIds, pairs) {
if (typeof requested !== "string" || knownIds.has(requested)) return requested;
for (const [oldId, newId2] of pairs) {
if (requested === oldId && knownIds.has(newId2)) return newId2;
if (requested === newId2 && knownIds.has(oldId)) return oldId;
}
return requested;
}
function canonicalRouteId(harness, model) {
if (typeof harness !== "string" || typeof model !== "string" || !harness || !model) return void 0;
const parts = model.split("/").filter((part) => part.length > 0);
if (parts.length === 0) return void 0;
const slug = parts[parts.length - 1].replaceAll(".", "-").toLowerCase();
const provider = parts.length > 1 ? parts[0].replaceAll(".", "-").toLowerCase() : void 0;
const id = provider ? `${harness}-${slug}-${provider}` : `${harness}-${slug}`;
return /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(id) && id.length <= 64 ? id : void 0;
}
function aliasList(value) {
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function lookupById(records, requested, kind) {
const list = [...records].filter((record2) => typeof record2?.id === "string" && record2.id.length > 0);
const known = new Set(list.map((record2) => record2.id));
const direct = list.find((record2) => record2.id === requested);
if (direct) return { record: direct, viaAlias: false };
for (const record2 of list) {
if (aliasList(record2.aliases).includes(requested)) {
noteDeprecatedId(kind, requested, record2.id);
return { record: record2, viaAlias: true };
}
}
const renamed = resolveRenamedId(requested, known, RENAMES[kind] ?? []);
if (renamed !== requested) {
const record2 = list.find((item) => item.id === renamed);
if (record2) {
noteDeprecatedId(kind, requested, renamed);
return { record: record2, viaAlias: true };
}
}
return void 0;
}
function findYamlBasename(directory, requested, kind) {
if (typeof requested !== "string" || !requested) return void 0;
if (existsSync(join(directory, `${requested}.yaml`))) return requested;
if (!existsSync(directory)) return void 0;
const found = [];
for (const name of readdirSync(directory)) {
if (!name.endsWith(".yaml") || name === "inventory.yaml") continue;
const id = name.slice(0, -5);
let doc;
try {
doc = import_yaml2.default.parse(readFileSync(join(directory, name), "utf8"));
} catch {
continue;
}
const aliases = doc && typeof doc === "object" ? aliasList(doc.aliases) : [];
found.push({ id, aliases });
}
const hit = lookupById(found, requested, kind);
return hit?.record.id;
}
function readYamlDir(directory, skipInventory) {
if (!existsSync(directory)) return [];
const docs = [];
for (const name of readdirSync(directory)) {
if (!name.endsWith(".yaml")) continue;
const id = name.slice(0, -5);
if (skipInventory && id === "inventory") continue;
let doc;
try {
doc = import_yaml2.default.parse(readFileSync(join(directory, name), "utf8"));
} catch (error) {
docs.push({ id, file: `${directory}/${name}`, error: error instanceof Error ? error.message : "invalid YAML" });
continue;
}
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
docs.push({ id, file: `${directory}/${name}`, error: "root must be a mapping" });
continue;
}
docs.push({ id, file: name, doc });
}
return docs;
}
function push(bucket, severity, code, file, message) {
bucket.push({ severity, code, file, message });
}
function selectorsFor(doc) {
const model = typeof doc.model === "string" ? doc.model : "";
const vendor = typeof doc.vendor === "string" ? doc.vendor : "";
const harness = typeof doc.harness === "string" ? doc.harness : "";
return [model, vendor && model ? `${vendor}/${model}` : "", harness && model ? `${harness}/${model}` : ""].filter(Boolean);
}
function lintWorkforce(root) {
const errors = [];
const warnings = [];
const models = readYamlDir(join(root, ".kxm", "models"), true).filter((entry) => !entry.error);
for (const entry of readYamlDir(join(root, ".kxm", "models"), true)) {
if (entry.error) push(errors, "error", "invalid_yaml", `.kxm/models/${entry.id}.yaml`, entry.error);
}
const roles = readYamlDir(join(root, ".kxm", "roles"), false).filter((entry) => !entry.error);
const agents = readYamlDir(join(root, ".kxm", "agents"), false).filter((entry) => !entry.error);
const workflows = readYamlDir(join(root, ".kxm", "workflows"), false).filter((entry) => !entry.error);
let admitted = [];
const routesFile = join(root, ".kxm", "routes.yaml");
if (existsSync(routesFile)) {
try {
const policy = import_yaml2.default.parse(readFileSync(routesFile, "utf8"));
admitted = Array.isArray(policy?.admitted) ? policy.admitted.filter((item) => typeof item === "string") : [];
} catch (error) {
push(errors, "error", "invalid_yaml", ".kxm/routes.yaml", error instanceof Error ? error.message : "invalid YAML");
}
}
const modelRecords = models.map((entry) => ({ id: entry.id, aliases: aliasList(entry.doc.aliases), entry }));
const used = /* @__PURE__ */ new Set();
for (const role of roles) {
const purpose = role.doc.purpose;
if (typeof purpose === "string" && role.id !== purpose) {
push(errors, "error", "role_id_convention", `.kxm/roles/${role.id}.yaml`, `role id '${role.id}' must equal purpose '${purpose}'`);
}
const roster = Array.isArray(role.doc.roster) ? role.doc.roster : [];
for (const item of roster) {
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
const route = item.route;
const effort = item.effort;
const routeLabel = typeof route === "string" && route ? route : "(missing route)";
if (typeof effort !== "string" || !ROSTER_EFFORTS.has(effort)) {
const detail = typeof effort === "string" ? `effort '${effort}' is not one of off, minimal, low, medium, high, xhigh, max` : "has no effort";
push(errors, "error", "roster_effort_required", `.kxm/roles/${role.id}.yaml`, `roster route '${routeLabel}' ${detail}`);
}
if (typeof route !== "string" || !route) continue;
const found = lookupById(modelRecords, route, "route");
if (!found) {
push(errors, "error", "route_unknown", `.kxm/roles/${role.id}.yaml`, `roster route '${route}' does not match a model file`);
continue;
}
used.add(found.record.id);
if (found.viaAlias) {
push(warnings, "warning", "deprecated_id", `.kxm/roles/${role.id}.yaml`, `roster route '${route}' is a deprecated alias of '${found.record.id}'`);
}
}
}
const covered = /* @__PURE__ */ new Set();
for (const model of models) {
const doc = model.doc;
if (typeof doc.id === "string" && doc.id !== model.id) {
push(errors, "error", "route_id_convention", `.kxm/models/${model.id}.yaml`, `declared id '${doc.id}' does not match the filename`);
}
const expected = canonicalRouteId(doc.harness, doc.model);
if (!expected || model.id !== expected) {
push(errors, "error", "route_id_convention", `.kxm/models/${model.id}.yaml`, `route id '${model.id}' must be '${expected ?? "<harness>-<model-slug>[-<provider>]"}'`);
}
if (!used.has(model.id)) {
push(errors, "error", "route_unused", `.kxm/models/${model.id}.yaml`, `route '${model.id}' is not on any role roster`);
}
const selectorHit = selectorsFor(doc).find((selector) => admitted.includes(selector));
if (!selectorHit) {
push(errors, "error", "route_not_admitted", `.kxm/models/${model.id}.yaml`, `model '${doc.model ?? ""}' is not an admitted selector`);
} else {
covered.add(selectorHit);
}
}
for (const selector of admitted) {
if (!covered.has(selector)) {
push(warnings, "warning", "admitted_unrouted", ".kxm/routes.yaml", `admitted model '${selector}' is not used by any route`);
}
}
const agentRecords = agents.map((entry) => ({ id: entry.id, aliases: aliasList(entry.doc.aliases), entry }));
for (const agent of agents) {
const role = agent.doc.role;
if (typeof role !== "string" || agent.id !== role) {
push(errors, "error", "agent_id_convention", `.kxm/agents/${agent.id}.yaml`, `agent id '${agent.id}' must equal its role '${role ?? ""}'`);
}
}
for (const workflow of workflows) {
if (!RESERVED_WORKFLOW_IDS.has(workflow.id) && !ROLE_IDS.some((role) => workflow.id === `${role}-only`)) {
push(errors, "error", "workflow_id_convention", `.kxm/workflows/${workflow.id}.yaml`, `workflow id '${workflow.id}' must be default, land, or <role>-only`);
}
const steps = Array.isArray(workflow.doc.steps) ? workflow.doc.steps : [];
const realIds = new Set(steps.map((step) => step && typeof step.id === "string" ? step.id : "").filter(Boolean));
for (const step of steps) {
if (!step || typeof step !== "object" || typeof step.id !== "string") continue;
if (step.kind === "agent" || step.kind === "moa") {
const agentName = typeof step.agent === "string" ? step.agent : "";
const found = agentName ? lookupById(agentRecords, agentName, "agent") : void 0;
if (!found) {
push(errors, "error", "agent_unknown", `.kxm/workflows/${workflow.id}.yaml`, `step '${step.id}' references unknown agent '${agentName}'`);
} else if (found.viaAlias) {
push(warnings, "warning", "deprecated_id", `.kxm/workflows/${workflow.id}.yaml`, `step '${step.id}' agent '${agentName}' is a deprecated alias of '${found.record.id}'`);
}
const role = found?.record.entry.doc.role;
if (typeof role === "string" && step.id !== role) {
push(errors, "error", "step_id_convention", `.kxm/workflows/${workflow.id}.yaml`, `agent step '${step.id}' must use the role id '${role}'`);
}
} else if (step.kind === "gate") {
const gate = typeof step.gate === "string" ? step.gate : "";
const allowed = step.id === "verify" || step.id === gate || step.id.startsWith(`${workflow.id}-`);
if (!allowed) {
push(errors, "error", "step_id_convention", `.kxm/workflows/${workflow.id}.yaml`, `gate step '${step.id}' must be verify, the gate id, or ${workflow.id}-<name>`);
}
}
for (const alias of aliasList(step.aliases)) {
if (realIds.has(alias) && alias !== step.id) {
push(errors, "error", "step_id_convention", `.kxm/workflows/${workflow.id}.yaml`, `step alias '${alias}' collides with another step id`);
}
}
}
}
return { errors, warnings };
}
// plugins/kxm/src/template.ts
var import_yaml3 = __toESM(require_dist(), 1);
import { createHash as createHash2 } from "node:crypto";
var KXM_TEMPLATE_ID = "builtin-minimal";
var KXM_TEMPLATE_PROVENANCE_PATH = ".kxm/template-provenance.yaml";
var CURRENT_KXM_TEMPLATE_VARIANT = "v4-registry";
var SUPPORTED_KXM_TEMPLATE_VARIANTS = ["v1", "v2", "v3-policy", "v4-registry"];
function compareCodeUnits3(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
function canonicalJson(value) {
if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
return JSON.stringify(value);
}
if (Array.isArray(value)) return `[${value.map((candidate) => canonicalJson(candidate)).join(",")}]`;
return `{${Object.keys(value).sort(compareCodeUnits3).map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
}
function kxmContentSha256(input) {
return `sha256:${createHash2("sha256").update(input).digest("hex")}`;
}
function authorityProjection(value) {
const projected = structuredClone(value);
if (projected.schema === "kxm.project.v1") delete projected.name;
if (projected.schema === "kxm.repository.v1") delete projected.description;
if (projected.schema === "kxm.agent.v1") delete projected.purpose;
if (projected.schema === "kxm.workflow.v1") delete projected.description;
return projected;
}
function kxmAuthoritySha256(value) {
return kxmContentSha256(canonicalJson(authorityProjection(value)));
}
function coreTemplate(projectId, projectName, variant) {
const files = /* @__PURE__ */ new Map([
[".kxm/project.yaml", {
schema: "kxm.project.v1",
id: projectId,
name: projectName,
defaultWorkflow: "default",
defaultExecutor: "local",
defaultHarness: "pi",
repositories: [{ id: "control", role: "control", required: true, pathHint: "." }],
workspace: {
dirtySnapshot: {
untracked: "ask",
dirtySubmodules: "fail"
}
}
}],
[".kxm/repo/repo.yaml", {
schema: "kxm.repository.v1",
projectId,
repositoryId: "control",
description: "Authoritative project configuration and repository content.",
defaultAccess: "write"
}],
[".kxm/agents/coordinator.yaml", {
schema: "kxm.agent.v1",
purpose: variant === "v1" || variant === "v4-registry" ? "Coordinate the pinned workflow and emit schema-validated commands." : "Coordinate the pinned workflow and emit validated, reviewable commands.",
tools: { preset: "coordinator" },
defaultRepositoryAccess: "read",
repositories: { control: variant === "v3-policy" ? "write" : "read" },
network: "provider-only",
resultSchema: "kxm.assignment-result.v1"
}],
[".kxm/agents/implementer.yaml", {
schema: "kxm.agent.v1",
purpose: "Implement the approved change within the declared repository scope.",
tools: { preset: "workspace-writer" },
defaultRepositoryAccess: "none",
repositories: { control: "write" },
network: "provider-only",
resultSchema: "kxm.assignment-result.v1"
}],
[".kxm/workflows/default.yaml", {
schema: "kxm.workflow.v1",
description: "Plan, implement, and verify a local change.",
coordinator: "coordinator",
limits: {
maxTransitions: 8,
maxRunDurationMs: 144e5,
maxAgentTimeMs: 216e5
},
steps: [
{
id: "plan",
kind: "agent",
agent: "coordinator",
maxAttempts: 2,
repositories: { control: "read" },
requiredEvidence: [{ key: "plan", kind: "artifact" }],
timeoutMs: 12e5,
on: {
passed: "implement",
blocked: { target: "$terminal", terminalStatus: "failed" }
}
},
{
id: "implement",
kind: "agent",
agent: "implementer",
maxAttempts: 3,
repositories: { control: "write" },
assignments: {
allowedAgents: ["implementer"],
minimum: 1,
target: 1,
maximum: 1,
maxParallel: 1,
maxAttemptsPerAssignment: 2,
maxWriteRepositories: 1
},
requiredEvidence: [{ key: "implementation-diff", kind: "artifact" }],
timeoutMs: 36e5,
on: {
passed: "verify",
failed: { target: "$terminal", terminalStatus: "failed" },
blocked: { target: "$terminal", terminalStatus: "failed" }
}
},
{
id: "verify",
kind: "gate",
gate: "test",
maxAttempts: 3,
repositories: { control: "write" },
requiredEvidence: [{ key: "local-gates", kind: "gate" }],
timeoutMs: 36e5,
on: {
passed: { target: "$terminal", terminalStatus: "completed" },
"implementation-failure": { target: "implement", maxTransitions: 3 },
failed: { target: "$terminal", terminalStatus: "failed" }
}
}
]
}]
]);
if (variant === "v4-registry") {
const coordinator = files.get(".kxm/agents/coordinator.yaml");
if (coordinator) {
files.delete(".kxm/agents/coordinator.yaml");
files.set(".kxm/agents/planner.yaml", { ...coordinator, role: "planner", aliases: ["coordinator"] });
}
const implementer = files.get(".kxm/agents/implementer.yaml");
if (implementer) {
files.delete(".kxm/agents/implementer.yaml");
files.set(".kxm/agents/writer.yaml", { ...implementer, role: "writer", aliases: ["implementer"] });
}
const workflow = files.get(".kxm/workflows/default.yaml");
if (workflow) {
const limits = { ...workflow.limits };
delete limits.maxAgentTimeMs;
const steps = workflow.steps.map((step) => {
if (step.id === "plan") {
const on = { ...step.on, passed: "writer" };
return { ...step, agent: "planner", on };
}
if (step.id === "implement") {
const assignments = { ...step.assignments, allowedAgents: ["writer"] };
return { ...step, id: "writer", aliases: ["implement"], agent: "writer", assignments };
}
if (step.id === "verify") {
const on = { ...step.on };
const failure = on["implementation-failure"];
if (failure && typeof failure === "object" && !Array.isArray(failure)) {
on["implementation-failure"] = { ...failure, target: "writer" };
}
return { ...step, on };
}
return step;
});
files.set(".kxm/workflows/default.yaml", { ...workflow, coordinator: "planner", limits, steps });
}
files.set(".kxm/routes.yaml", {
schema: "kxm.routes.v2",
updatedAt: "2026-09-27T00:00:00.000Z",
admitted: ["anthropic/fable", "xai/grok-4.6"],
disabled: []
});
files.set(".kxm/models/grok-grok-4-6.yaml", {
schema: "kxm.model.v2",
id: "grok-grok-4-6",
aliases: ["grok-default"],
harness: "grok",
model: "grok-4.6",
vendor: "xai",
status: "admitted",
permissions: ["edit"]
});
files.set(".kxm/models/claude-fable.yaml", {
schema: "kxm.model.v2",
id: "claude-fable",
aliases: ["fable-default"],
harness: "claude",
model: "fable",
vendor: "anthropic",
status: "admitted",
permissions: ["read-only"]
});
files.set(".kxm/roles/writer.yaml", {
schema: "kxm.role.v2",
id: "writer",
purpose: "writer",
permission: "edit",
description: "Primary implementation agent.",
roster: [{ route: "grok-grok-4-6", effort: "medium" }]
});
files.set(".kxm/roles/planner.yaml", {
schema: "kxm.role.v2",
id: "planner",
purpose: "planner",
permission: "read-only",
description: "Plans the change before implementation.",
roster: [{ route: "claude-fable", effort: "medium" }]
});
files.set(".kxm/gates.yaml", {
schema: "kxm.gate-registry.v1",
gates: { test: { kind: "command", argv: ["npm", "test"], timeoutMs: 36e5 } }
});
}
return files;
}
function provenanceRevision(files) {
return kxmContentSha256(canonicalJson(files.map((file) => ({
path: file.path,
sha256: file.sha256,
authoritySha256: file.authoritySha256,
bytes: file.bytes
}))));
}
function renderKxmTemplate(projectId, projectName, variant = CURRENT_KXM_TEMPLATE_VARIANT) {
const values = coreTemplate(projectId, projectName, variant);
const coreFiles = /* @__PURE__ */ new Map();
const records = [...values.entries()].map(([path, value]) => {
const bytes = Buffer.from((0, import_yaml3.stringify)(value, { lineWidth: 0 }), "utf8");
coreFiles.set(path, bytes);
return {
path,
sha256: kxmContentSha256(bytes),
authoritySha256: kxmAuthoritySha256(value),
bytes: bytes.byteLength
};
}).sort((left, right) => compareCodeUnits3(left.path, right.path));
const templateRevision = provenanceRevision(records);
const provenance = {
schema: "kxm.template-provenance.v1",
templateId: KXM_TEMPLATE_ID,
templateRevision,
inputs: { projectId, projectName },
files: records
};
const fileEntries = [...coreFiles.entries()];
fileEntries.push([
KXM_TEMPLATE_PROVENANCE_PATH,
Buffer.from((0, import_yaml3.stringify)(provenance, { lineWidth: 0 }), "utf8")
]);
fileEntries.sort(([left], [right]) => compareCodeUnits3(left, right));
const files = new Map(fileEntries);
return { projectId, projectName, templateRevision, provenance, files, values };
}
function validatedTemplateProvenance(value) {
if (value.schema !== "kxm.template-provenance.v1" || value.templateId !== KXM_TEMPLATE_ID) return void 0;
const candidate = value;
return provenanceRevision(candidate.files) === candidate.templateRevision ? candidate : void 0;
}
function resolveKxmTemplateBaseline(value) {
const candidate = validatedTemplateProvenance(value);
if (!candidate) return void 0;
for (const variant of SUPPORTED_KXM_TEMPLATE_VARIANTS) {
const known = renderKxmTemplate(candidate.inputs.projectId, candidate.inputs.projectName, variant).provenance;
if (known.templateRevision === candidate.templateRevision && canonicalJson(known) === canonicalJson(candidate)) {
return candidate;
}
}
return void 0;
}
// plugins/kxm/src/repo-root.ts
import { existsSync as existsSync2 } from "node:fs";
import { dirname, join as join2 } from "node:path";
import { fileURLToPath } from "node:url";
var ROOT_MARKERS = ["scripts/kxm-hub.mjs", "scripts/kxm.mjs"];
var MAX_WALK_DEPTH = 10;
function tryFindKxmRepoRoot(fromUrl = import.meta.url) {
let dir = dirname(fileURLToPath(fromUrl));
for (let depth = 0; depth < MAX_WALK_DEPTH; depth += 1) {
if (ROOT_MARKERS.some((marker) => existsSync2(join2(dir, marker)))) return dir;
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
return void 0;
}
function findKxmRepoRoot(fromUrl = import.meta.url) {
const found = tryFindKxmRepoRoot(fromUrl);
if (found !== void 0) return found;
throw new Error(
`kxm: cannot locate the KXM repo root from ${fileURLToPath(fromUrl)} (walked ${MAX_WALK_DEPTH} levels looking for ${ROOT_MARKERS[0]})`
);
}
// plugins/kxm/src/harness.ts
import { spawnSync } from "node:child_process";
import { existsSync as existsSync3 } from "node:fs";
import { win32 as win32Path } from "node:path";
// plugins/kxm/src/oneshot-process.ts
import { spawn } from "node:child_process";
var OUTPUT_LIMIT = 8 * 1024 * 1024;
var KILL_GRACE_MS = 250;
var DRAIN_GRACE_MS = 500;
var REAP_GRACE_MS = 1e3;
function killProcessTree(child, signal = "SIGKILL") {
if (process.platform !== "win32" && child.pid) {
try {
process.kill(-child.pid, signal);
return;
} catch {
}
}
try {
child.kill(signal);
} catch {
}
}
function defaultSpawn(command, args, options) {
if (options.signal?.aborted) {
return Promise.resolve({ stdout: "", stderr: "", code: null, started: false, observedChildExit: false, error: new Error("process_aborted") });
}
return new Promise((resolve15) => {
const stdout = [];
const stderr = [];
let outputBytes = 0;
let outputChunks = 0;
let code = null;
let signal = null;
let observedChildExit = false;
let finished = false;
let stopping = false;
let closed = false;
let killSent = false;
let error;
let wallTimer;
let killTimer;
let drainTimer;
let reapTimer;
let child;
const finish = () => {
if (finished) return;
if (stopping && !killSent) return;
finished = true;
for (const timer of [wallTimer, killTimer, drainTimer, reapTimer]) clearTimeout(timer);
options.signal?.removeEventListener("abort", onAbort);
child?.stdin?.destroy();
child?.stdout?.destroy();
child?.stderr?.destroy();
child?.unref();
const started = Boolean(child?.pid);
if (started && !observedChildExit) error ??= new Error("process_exit_unobserved");
const unverifiedDescendants = stopping || started && !observedChildExit;
resolve15({
stdout: Buffer.concat(stdout).toString("utf8"),
stderr: Buffer.concat(stderr).toString("utf8"),
code,
signal,
started,
observedChildExit,
terminationRequested: stopping,
...unverifiedDescendants ? { unverifiedDescendants: true } : {},
...error ? { error } : {}
});
};
const kill = (requested) => {
killProcessTree(child, requested);
};
const stop = (reason) => {
if (finished) return;
error ??= new Error(reason);
if (stopping) return;
stopping = true;
clearTimeout(wallTimer);
kill("SIGTERM");
killTimer = setTimeout(() => {
kill("SIGKILL");
killSent = true;
if (closed) {
finish();
return;
}
reapTimer = setTimeout(() => {
if (!observedChildExit) error ??= new Error("process_exit_unobserved");
finish();
}, REAP_GRACE_MS);
}, KILL_GRACE_MS);
};
const onAbort = () => stop("process_aborted");
try {
child = spawn(command, [...args], {
cwd: options.cwd,
env: options.env ?? process.env,
stdio: ["pipe", "pipe", "pipe"],
shell: options.shell === true,
windowsHide: true,
detached: process.platform !== "win32"
});
} catch (cause) {
error = cause instanceof Error ? cause : new Error("process_spawn_failed");
finish();
return;
}
const collect = (target, chunk) => {
if (finished) return;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
const remaining = Math.max(0, OUTPUT_LIMIT - outputBytes);
if (remaining && outputChunks < 16384) {
const kept = bytes.subarray(0, remaining);
target.push(kept);
outputBytes += kept.length;
outputChunks++;
}
if (bytes.length > remaining || outputChunks >= 16384) stop("process_output_limit");
};
child.stdout.on("data", (chunk) => collect(stdout, chunk));
child.stderr.on("data", (chunk) => collect(stderr, chunk));
child.stdin.on("error", () => stop("process_stdin_error"));
child.stdout.on("error", () => stop("process_stdio_error"));
child.stderr.on("error", () => stop("process_stdio_error"));
child.on("error", (cause) => {
error ??= cause;
if (!child.pid) finish();
else stop("process_error");
});
child.on("exit", (exitCode, exitSignal) => {
if (finished) return;
observedChildExit = true;
code = exitCode;
signal = exitSignal;
clearTimeout(wallTimer);
drainTimer = setTimeout(() => stop("process_stdio_unclosed"), DRAIN_GRACE_MS);
});
child.on("close", (exitCode, exitSignal) => {
if (finished) return;
closed = true;
code = exitCode;
signal = exitSignal;
finish();
});
options.signal?.addEventListener("abort", onAbort, { once: true });
if (options.signal?.aborted) onAbort();
const timeoutMs = options.timeoutMs ?? 12e4;
if (!stopping) wallTimer = setTimeout(() => stop("process_timeout"), timeoutMs > 0 && Number.isFinite(timeoutMs) ? timeoutMs : 12e4);
try {
child.stdin.end(options.input);
} catch {
stop("process_stdin_error");
}
});
}
// plugins/kxm/src/harness.ts
var DEFAULT_HARNESS = "pi";
var UNKNOWN_AUTH_HARNESSES = /* @__PURE__ */ new Set(["deepseek"]);
var GROK_LOGIN_LINE = "You are logged in with grok.com.";
var AGY_MODEL_ROW = /^[a-z0-9]+(?:[._-][a-z0-9]+)+\s+\S/im;
var CODEX_CHATGPT_LINE = "Logged in using ChatGPT";
var CODEX_API_KEY_PREFIX = "Logged in using an API key";
var CODEX_NEGATIVE_LINE = "Not logged in";
var NATIVE_HARNESS_PROVIDERS = Object.freeze({
claude: "anthropic",
codex: "openai",
grok: "xai",
agy: "google",
kimi: "moonshot",
deepseek: "deepseek"
});
var PI_ALLOWED_PROVIDERS = Object.freeze([
"openrouter",
"nous-portal",
"nous",
"nous-proxy"
]);
var PI_NATIVE_BRAKE_PROVIDERS = Object.freeze([
"anthropic",
"openai",
"xai",
"moonshot",
"google",
"deepseek"
]);
var PI_VENDOR_OWNED_PROVIDERS = Object.freeze({
"openai-codex": "openai",
moonshotai: "moonshot",
"moonshotai-cn": "moonshot",
"kimi-coding": "moonshot",
"google-vertex": "google",
// Claude subscription via the Agent SDK: experiment-only, never a product route.
"claude-bridge": "anthropic",
// The decided Google route, for Gemini ids only (see PI_ANTIGRAVITY_MODEL_ID).
antigravity: "google"
});
var PI_VENDOR_SEGMENT_ALIASES = Object.freeze({
"x-ai": "xai",
moonshotai: "moonshot",
"google-ai": "google"
});
var PI_ANTIGRAVITY_MODEL_ID = /^gemini-[a-z0-9.-]+$/;
function reportedModelId(value) {
return typeof value === "string" && /^[a-z0-9][a-z0-9._:/-]{0,199}$/i.test(value) ? value : void 0;
}
function parseClaudeOneShotUsage(stdout, stderr, requestedModel) {
const trimmed = stdout.trim();
if (!trimmed) {
return {
text: "",
isError: true,
errorMessage: stderr.trim() || "empty stdout from claude"
};
}
try {
const payload = JSON.parse(trimmed);
const usage = payload.usage ?? {};
const entries = payload.modelUsage && typeof payload.modelUsage === "object" && !Array.isArray(payload.modelUsage) ? Object.entries(payload.modelUsage).filter(([, value]) => value && typeof value === "object") : [];
const matches = entries.filter(([model]) => model === requestedModel || requestedModel && (model.startsWith(`${requestedModel}-`) || model.startsWith(`claude-${requestedModel}-`)));
const selected = matches.length === 1 ? matches[0] : entries.length === 1 ? entries[0] : void 0;
const modelUsageDetail = selected?.[1];
const effectiveModel = reportedModelId(payload.model) ?? reportedModelId(selected?.[0]);
const tokensIn = (typeof usage.input_tokens === "number" ? usage.input_tokens : void 0) ?? (typeof modelUsageDetail?.inputTokens === "number" ? modelUsageDetail.inputTokens : null);
const tokensOut = (typeof usage.output_tokens === "number" ? usage.output_tokens : void 0) ?? (typeof modelUsageDetail?.outputTokens === "number" ? modelUsageDetail.outputTokens : null);
const cacheReadTokens = (typeof usage.cache_read_input_tokens === "number" ? usage.cache_read_input_tokens : void 0) ?? (typeof modelUsageDetail?.cacheReadInputTokens === "number" ? modelUsageDetail.cacheReadInputTokens : null);
const cacheWriteTokens = (typeof usage.cache_creation_input_tokens === "number" ? usage.cache_creation_input_tokens : void 0) ?? (typeof modelUsageDetail?.cacheCreationInputTokens === "number" ? modelUsageDetail.cacheCreationInputTokens : null);
const costUsd = typeof payload.total_cost_usd === "number" ? payload.total_cost_usd : typeof modelUsageDetail?.costUSD === "number" ? modelUsageDetail.costUSD : null;
const isError = Boolean(payload.is_error || payload.error || ["error", "aborted", "failed", "max_tokens", "length"].includes(String(payload.stopReason ?? payload.stop_reason ?? "")));
const text = typeof payload.result === "string" ? payload.result : typeof payload.text === "string" ? payload.text : "";
const errorMessage = isError ? typeof payload.error === "string" ? payload.error : typeof payload.error?.message === "string" ? payload.error.message : text : void 0;
return {
text,
effectiveModel,
isError,
errorMessage,
usage: {
tokensIn,
tokensOut,
cacheReadTokens,
cacheWriteTokens,
contextTokens: null,
costUsd
}
};
} catch {
return {
text: trimmed,
isError: true,
errorMessage: "invalid Claude JSON response",
usage: {}
};
}
}
function parseGrokOneShotUsage(stdout, stderr, requestedModel) {
return parseClaudeOneShotUsage(stdout, stderr, requestedModel);
}
function parseCodexOneShotUsage(stdout, stderr) {
const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
if (lines.length === 0) {
return {
text: "",
isError: true,
errorMessage: stderr.trim() || "empty stdout from codex"
};
}
const events = [];
for (const line of lines) {
try {
const parsed = JSON.parse(line);
if (parsed && typeof parsed === "object") events.push(parsed);
} catch {
}
}
const messageTexts = [];
let usage;
let hasError = false;
let errorMessage;
for (const ev of events) {
if (ev.type === "turn.failed" || ev.type === "error") {
hasError = true;
errorMessage = typeof ev.message === "string" ? ev.message : typeof ev.error?.message === "string" ? ev.error.message : "turn_failed";
}
if (ev.type === "item.completed" && ev.item && typeof ev.item === "object" && ev.item.type === "agent_message") {
const t = ev.item.text;
if (typeof t === "string") messageTexts.push(t);
}
if (ev.type === "turn.completed" && ev.usage && typeof ev.usage === "object") {
usage = ev.usage;
}
}
const text = (messageTexts.at(-1) ?? "").trim();
if (!events.some((event) => event.type === "turn.completed") || !text) hasError = true;
const tokensIn = typeof usage?.input_tokens === "number" ? usage.input_tokens : null;
const tokensOut = typeof usage?.output_tokens === "number" ? usage.output_tokens : null;
const cacheReadTokens = typeof usage?.cached_input_tokens === "number" ? usage.cached_input_tokens : null;
const cacheWriteTokens = typeof usage?.cache_write_input_tokens === "number" ? usage.cache_write_input_tokens : null;
return {
text,
isError: hasError,
errorMessage,
usage: {
tokensIn,
tokensOut,
cacheReadTokens,
cacheWriteTokens,
contextTokens: null,
costUsd: null
}
};
}
function parsePiOneShotUsage(stdout, _stderr) {
let finalMessage;
for (const line of stdout.split("\n")) {
const trimmed = line.trim();
if (!trimmed.startsWith("{")) continue;
try {
const event = JSON.parse(trimmed);
if (event.type !== "message_end" && event.type !== "turn_end") continue;
const message = event.message;
if (!message || message.role !== "assistant") continue;
finalMessage = message;
} catch {
}
}
if (!finalMessage) {
return { text: "", isError: true, usage: {} };
}
const content = Array.isArray(finalMessage.content) ? finalMessage.content : [];
const text = content.map((part) => part && typeof part === "object" && part.type === "text" ? String(part.text ?? "") : "").filter((part) => part.length > 0).join("\n");
const effectiveModel = reportedModelId(finalMessage.model);
const rawUsage = finalMessage.usage;
const usage = rawUsage && typeof rawUsage === "object" ? {
tokensIn: typeof rawUsage.input === "number" ? rawUsage.input : null,
tokensOut: typeof rawUsage.output === "number" ? rawUsage.output : null,
cacheReadTokens: typeof rawUsage.cacheRead === "number" ? rawUsage.cacheRead : null,
cacheWriteTokens: typeof rawUsage.cacheWrite === "number" ? rawUsage.cacheWrite : null,
contextTokens: null,
costUsd: null
} : {};
const stopReason = typeof finalMessage.stopReason === "string" ? finalMessage.stopReason : void 0;
const terminalError = stopReason === "error" || stopReason === "aborted";
if (terminalError || text.length === 0) {
return { text, isError: true, ...effectiveModel !== void 0 ? { effectiveModel } : {}, usage };
}
return { text, ...effectiveModel !== void 0 ? { effectiveModel } : {}, usage };
}
function parseGenericOneShotUsage(stdout, _stderr) {
const trimmed = stdout.trim();
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
const rec = parsed;
const text = typeof rec.result === "string" ? rec.result : typeof rec.text === "string" ? rec.text : typeof rec.response === "string" ? rec.response : trimmed;
const u = rec.usage && typeof rec.usage === "object" ? rec.usage : {};
return { text, effectiveModel: reportedModelId(rec.model), isError: Boolean(rec.is_error || rec.error || rec.success === false), usage: {
tokensIn: typeof u.input_tokens === "number" ? u.input_tokens : null,
tokensOut: typeof u.output_tokens === "number" ? u.output_tokens : null,
cacheReadTokens: typeof u.cache_read_input_tokens === "number" ? u.cache_read_input_tokens : null,
cacheWriteTokens: typeof u.cache_creation_input_tokens === "number" ? u.cache_creation_input_tokens : null,
contextTokens: null,
costUsd: typeof rec.total_cost_usd === "number" ? rec.total_cost_usd : null
} };
}
} catch {
}
return { text: trimmed, usage: {} };
}
function parseKimiOneShotUsage(stdout, _stderr) {
const trimmed = stdout.trim();
const assistantTexts = [];
let isError = false;
let errorMessage;
for (const line of trimmed.split("\n")) {
const lineTrimmed = line.trim();
if (!lineTrimmed) continue;
try {
const parsed = JSON.parse(lineTrimmed);
if (parsed && typeof parsed === "object") {
const rec = parsed;
if (rec.role === "assistant" && typeof rec.content === "string") {
assistantTexts.push(rec.content);
} else if (rec.role === "error" || rec.type === "error") {
isError = true;
errorMessage = typeof rec.message === "string" ? rec.message : typeof rec.content === "string" ? rec.content : "kimi_error";
}
}
} catch {
}
}
const text = assistantTexts.length > 0 ? assistantTexts.join("\n") : trimmed;
return {
text,
isError,
errorMessage,
usage: {
tokensIn: null,
tokensOut: null,
cacheReadTokens: null,
cacheWriteTokens: null,
contextTokens: null,
costUsd: null
}
};
}
function parseAgyOneShotUsage(stdout, _stderr) {
const trimmed = stdout.trim();
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
const rec = parsed;
const text = typeof rec.response === "string" ? rec.response : typeof rec.result === "string" ? rec.result : trimmed;
const isError = rec.status === "ERROR";
const rawError = rec.error;
const errorMessage = isError ? typeof rawError === "string" ? rawError : typeof rawError?.message === "string" ? rawError.message : "agy_error" : void 0;
const usageRec = rec.usage && typeof rec.usage === "object" ? rec.usage : {};
const tokensIn = typeof usageRec.input_tokens === "number" ? usageRec.input_tokens : null;
const tokensOut = typeof usageRec.output_tokens === "number" ? usageRec.output_tokens : null;
const cacheReadTokens = typeof usageRec.cache_read_tokens === "number" ? usageRec.cache_read_tokens : null;
const contextTokens = typeof usageRec.total_tokens === "number" ? usageRec.total_tokens : tokensIn;
return {
text,
isError,
errorMessage,
usage: {
tokensIn,
tokensOut,
cacheReadTokens,
cacheWriteTokens: null,
contextTokens,
costUsd: null
}
};
}
} catch {
}
return {
text: trimmed,
usage: {
tokensIn: null,
tokensOut: null,
cacheReadTokens: null,
cacheWriteTokens: null,
contextTokens: null
}
};
}
var READ_ONLY_ONESHOT_ARGS = Object.freeze({
// pi: total containment for a one-shot witness — no tools (built-in, extension and
// custom), no ambient extension/hook discovery, no skills, no prompt templates, no
// AGENTS.md/CLAUDE.md context discovery, and an ephemeral session. `--no-tools` alone
// is not enough: extensions and hooks can still run with their own permissions.
pi: Object.freeze(["--no-tools", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-session"]),
omp: Object.freeze(["--no-tools", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-session"]),
claude: Object.freeze(["--tools", "Read,Glob,Grep", "--restricted", "--safe-mode", "--permission-mode", "plan", "--permission-prompts", "none", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disable-slash-commands", "--no-session-persistence"]),
codex: Object.freeze(["--sandbox", "read-only", "--ignore-user-config", "-c", 'approval_policy="never"']),
grok: Object.freeze(["--sandbox", "read-only", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--no-subagents", "--disable-web-search"]),
agy: Object.freeze(["--mode", "plan", "--sandbox", "--disable-slash-commands"]),
kimi: Object.freeze(["--plan"])
});
function oneShotReadOnlyArgs(harness) {
return Object.hasOwn(READ_ONLY_ONESHOT_ARGS, harness) ? READ_ONLY_ONESHOT_ARGS[harness] : void 0;
}
var WRITER_ONESHOT_ARGS = Object.freeze({
pi: Object.freeze(["-a", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-session"]),
omp: Object.freeze(["-a", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-session"]),
grok: Object.freeze(["--always-approve", "--no-subagents", "--disable-web-search"])
});
function oneShotWriterArgs(harness) {
return Object.hasOwn(WRITER_ONESHOT_ARGS, harness) ? WRITER_ONESHOT_ARGS[harness] : void 0;
}
function oneShotPermissionArgs(harness, permission) {
return permission === "edit" ? oneShotWriterArgs(harness) : oneShotReadOnlyArgs(harness);
}
var BUILTIN_HARNESSES = Object.freeze([
{
id: "pi",
label: "Pi",
default: true,
mode: "headless",
commands: ["pi"],
versionArgs: ["--version"],
update: {
self: ["update", "--self"],
extensions: ["update", "--extensions"],
models: ["update", "--models"]
},
oneShot: {
argv: ["-p", "--mode", "json"],
promptVia: "arg",
outputFormat: "json",
usageParser: parsePiOneShotUsage
}
},
{
id: "omp",
label: "Oh My Pi",
default: false,
mode: "headless",
commands: ["omp"],
versionArgs: ["--version"],
authArgs: ["models", "--json"],
update: {
self: ["update"],
extensions: ["plugin", "upgrade"],
models: ["models", "refresh"]
},
oneShot: {
argv: ["-p", ...oneShotReadOnlyArgs("omp"), "--mode", "json"],
promptVia: "arg",
outputFormat: "json",
usageParser: parsePiOneShotUsage
}
},
{
id: "claude",
label: "Claude Code",
default: false,
mode: "either",
commands: ["claude"],
versionArgs: ["--version"],
authArgs: ["auth", "status"],
update: {
self: ["update"],
extensions: ["plugin", "update", "kxm", "-y"]
},
oneShot: {
argv: ["-p", ...oneShotReadOnlyArgs("claude"), "--output-format", "json"],
promptVia: "stdin",
outputFormat: "json",
usageParser: parseClaudeOneShotUsage
}
},
{
id: "kimi",
label: "Kimi Code",
default: false,
mode: "either",
commands: ["kimi"],
versionArgs: ["--version"],
authArgs: ["provider", "list"],
update: { self: ["upgrade"] },
oneShot: {
argv: [...oneShotReadOnlyArgs("kimi"), "--output-format", "stream-json", "-p"],
promptVia: "arg",
outputFormat: "stream-json",
usageParser: parseKimiOneShotUsage
}
},
{
id: "codex",
label: "Codex",
default: false,
mode: "either",
commands: ["codex"],
versionArgs: ["--version"],
authArgs: ["login", "status"],
update: { self: ["update"] },
oneShot: {
argv: ["exec", ...oneShotReadOnlyArgs("codex"), "--json", "-"],
promptVia: "stdin",
outputFormat: "json",
usageParser: parseCodexOneShotUsage
}
},
{
id: "deepseek",
label: "DeepSeek",
default: false,
mode: "either",
commands: ["deepseek"],
versionArgs: ["--version"],
update: { self: ["update"] },
oneShot: {
argv: ["--json"],
promptVia: "stdin",
outputFormat: "json",
usageParser: parseGenericOneShotUsage
}
},
{
id: "grok",
label: "Grok CLI",
default: false,
mode: "either",
commands: ["grok"],
versionArgs: ["--version"],
authArgs: ["models"],
update: { self: ["update"] },
oneShot: {
argv: [...oneShotReadOnlyArgs("grok"), "--output-format", "json", "--single"],
promptVia: "arg",
outputFormat: "json",
usageParser: parseGrokOneShotUsage
}
},
{
id: "agy",
label: "Antigravity CLI",
default: false,
mode: "either",
commands: ["agy"],
versionArgs: ["--version"],
authArgs: ["models"],
update: { self: ["update"] },
oneShot: {
argv: [...oneShotReadOnlyArgs("agy"), "--output-format", "json", "-p"],
promptVia: "arg",
outputFormat: "json",
usageParser: parseAgyOneShotUsage
}
}
]);
var BUILTIN_HARNESS_IDS = BUILTIN_HARNESSES.map((entry) => entry.id);
function isKnownHarnessId(id, extra = []) {
if (BUILTIN_HARNESS_IDS.includes(id)) return true;
for (const candidate of extra) if (candidate === id) return true;
return false;
}
var SAFE_HARNESS_COMMAND_ID = /^[A-Za-z][A-Za-z0-9_-]*$/;
function harnessCommandCandidates(command, platform = process.platform) {
if (platform !== "win32" || !SAFE_HARNESS_COMMAND_ID.test(command)) return [command];
return [command, `${command}.exe`, `${command}.cmd`];
}
function isWindowsHarnessShim(command) {
return /\.(cmd|bat)$/i.test(command.replace(/\\/g, "/").split("/").pop() ?? command);
}
function harnessSpawnUsesShell(command, platform = process.platform) {
if (platform !== "win32") return false;
const base = command.replace(/\\/g, "/").split("/").pop() ?? "";
return /^[A-Za-z][A-Za-z0-9_-]*\.cmd$/i.test(base);
}
var WIN_NPM_INNER_EXE = Object.freeze({
claude: Object.freeze(["node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"])
});
function findWinNpmInnerExe(cliId, options = {}) {
if ((options.platform ?? process.platform) !== "win32") return void 0;
const segments = WIN_NPM_INNER_EXE[cliId];
if (!segments) return void 0;
const exists = options.existsSync ?? existsSync3;
const pathEnv = options.pathEnv ?? process.env.PATH ?? "";
for (const dir of pathEnv.split(";").filter(Boolean)) {
if (!exists(win32Path.join(dir, `${cliId}.cmd`))) continue;
const inner = win32Path.join(dir, ...segments);
if (exists(inner)) return inner;
}
return void 0;
}
function defaultRunner(env) {
return (command, args, timeoutMs) => {
try {
const result = spawnSync(command, [...args], {
encoding: "utf8",
timeout: timeoutMs,
windowsHide: true,
env,
shell: harnessSpawnUsesShell(command)
});
if (result.error) {
const code = result.error.code;
return { ok: false, code: result.status, stdout: "", stderr: result.stderr?.toString() ?? "", error: code ?? result.error.message };
}
return {
ok: result.status === 0,
code: result.status,
stdout: result.stdout?.toString() ?? "",
stderr: result.stderr?.toString() ?? ""
};
} catch (error) {
return { ok: false, code: null, stdout: "", stderr: "", error: error instanceof Error ? error.message : "spawn_failed" };
}
};
}
function commandResultFromSpawn(result) {
const errno = result.error && "code" in result.error ? result.error.code : void 0;
const error = (typeof errno === "string" && errno ? errno : void 0) ?? result.error?.message ?? (result.observedChildExit !== true ? "auth_probe_exit_unobserved" : void 0);
return {
ok: result.code === 0 && !error,
code: result.code,
stdout: result.stdout,
stderr: result.stderr,
...error ? { error } : {}
};
}
function defaultAsyncRunner(env, signal) {
return async (command, args, timeoutMs) => {
try {
return commandResultFromSpawn(await defaultSpawn(command, args, {
env,
timeoutMs,
signal,
shell: harnessSpawnUsesShell(command)
}));
} catch (error) {
return { ok: false, code: null, stdout: "", stderr: "", error: error instanceof Error ? error.message : "spawn_failed" };
}
};
}
function firstLine(text) {
const line = text.split(/\r?\n/).map((candidate) => candidate.trim()).find(Boolean);
return line && line.length <= 200 ? line : void 0;
}
function boundText(text, max = 4e3) {
const trimmed = text.trim();
if (!trimmed) return void 0;
return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}\u2026`;
}
function authLines(result) {
return `${result.stdout}
${result.stderr}`.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
}
function parseJsonObject(text) {
try {
const value = JSON.parse(text.trim());
if (value && typeof value === "object" && !Array.isArray(value)) return value;
} catch {
}
return void 0;
}
function authConflictIssue(result) {
const fields = [];
const okTrue = result.ok === true;
const codeZero = result.code === 0;
if (okTrue !== codeZero) fields.push("ok", "code");
if (okTrue && result.error) {
if (!fields.includes("ok")) fields.push("ok");
fields.push("error");
}
return fields.length > 0 ? `auth_conflict:${fields.join(",")}` : void 0;
}
function commandSucceeded(result) {
return result.ok === true && result.code === 0 && !result.error;
}
function isCodexApiKeyLine(line) {
return line === CODEX_API_KEY_PREFIX || line.startsWith(`${CODEX_API_KEY_PREFIX} - `);
}
function interpretAuth(id, result) {
const conflict = authConflictIssue(result);
if (conflict) return { authenticated: null, issues: [conflict] };
if (result.error) return { authenticated: null, issues: ["auth_probe_error"] };
const lines = authLines(result);
if (id === "claude") {
const payload = parseJsonObject(result.stdout);
if (payload && payload.loggedIn === false) return { authenticated: false, issues: ["not_authenticated"] };
if (commandSucceeded(result) && payload && payload.loggedIn === true) return {
authenticated: true,
issues: [],
...payload.authMethod === "claude.ai" || payload.authMethod === "api-key" ? { authMethod: payload.authMethod } : {}
};
return { authenticated: null, issues: ["auth_unparsed"] };
}
if (id === "codex") {
if (lines.some((line) => line === CODEX_NEGATIVE_LINE || line.startsWith(`${CODEX_NEGATIVE_LINE} `))) {
return { authenticated: false, issues: ["not_authenticated"] };
}
if (commandSucceeded(result) && lines.some((line) => line === CODEX_CHATGPT_LINE)) {
return { authenticated: true, authMethod: "ChatGPT", issues: [] };
}
if (commandSucceeded(result) && lines.some((line) => isCodexApiKeyLine(line))) {
return { authenticated: true, authMethod: "api-key", issues: ["auth_api_key"] };
}
return { authenticated: null, issues: ["auth_unparsed"] };
}
if (id === "grok") {
if (commandSucceeded(result) && lines.some((line) => line === GROK_LOGIN_LINE)) return { authenticated: true, issues: [] };
return { authenticated: null, issues: ["auth_unparsed"] };
}
if (id === "omp") {
if (commandSucceeded(result)) {
const payload = parseJsonObject(result.stdout);
if (payload && Array.isArray(payload.models) && payload.models.length > 0) {
return { authenticated: true, issues: [] };
}
if (commandSucceeded(result)) return { authenticated: true, issues: [] };
}
return { authenticated: null, issues: ["auth_unparsed"] };
}
if (id === "agy") {
const text = `${result.stdout}
${result.stderr}`;
if (!commandSucceeded(result) || !text.trim()) {
return { authenticated: false, issues: ["not_authenticated"] };
}
if (AGY_MODEL_ROW.test(text)) return { authenticated: true, authMethod: "antigravity-oauth", issues: [] };
return { authenticated: null, issues: ["auth_unparsed"] };
}
if (id === "kimi") {
if (!commandSucceeded(result)) {
return { authenticated: false, issues: ["not_authenticated"] };
}
if (lines.some((line) => /not logged in|no provider/i.test(line))) {
return { authenticated: false, issues: ["not_authenticated"] };
}
if (lines.some((line) => line.includes("managed:kimi") || line.includes("type=kimi") || line.includes("Default model:"))) {
return { authenticated: true, issues: [] };
}
return { authenticated: null, issues: ["auth_unparsed"] };
}
return { authenticated: null, issues: ["auth_unparsed"] };
}
function resolveDispatchStatus(entry, detected, authenticated, issues) {
if (!detected) {
return { status: "no", supported: false, reason: "not_detected" };
}
if (entry.id !== "pi" && !entry.oneShot) {
return {
status: "no",
supported: false,
reason: "no_headless_mode"
};
}
if (entry.id !== "pi" && !oneShotReadOnlyArgs(entry.id)) {
return { status: "no", supported: false, reason: "permission_profile_unaudited" };
}
if (authenticated === false) {
return { status: "no", supported: false, reason: "not_authenticated" };
}
if (authenticated === null) {
const authIssue = issues.find((issue4) => issue4 === "auth_context_required" || issue4 === "auth_unknown" || issue4 === "auth_unparsed" || issue4.startsWith("auth_"));
return { status: "no", supported: false, reason: authIssue ?? issues[0] ?? "auth_unknown" };
}
return { status: "yes", supported: true };
}
function windowsCmdReportsMissing(result) {
if (result.ok) return false;
const text = `${result.stdout}
${result.stderr}`;
return /not recognized as an internal or external command/i.test(text) || /the system cannot find the (?:file|path) specified/i.test(text);
}
function tryHarnessCommand(candidate, entry, runCommand, timeoutMs) {
const result = runCommand(candidate, entry.versionArgs, timeoutMs);
if (result.error === "ENOENT") return void 0;
if (result.error && result.code === null && !result.stdout && !result.stderr) return void 0;
if (isWindowsHarnessShim(candidate) && windowsCmdReportsMissing(result)) return void 0;
return {
command: candidate,
version: firstLine(result.stdout) ?? firstLine(result.stderr)
};
}
function detectHarnessCommand(entry, runCommand, timeoutMs, platform, probe = {}) {
const candidates = entry.commands.flatMap((base) => [...harnessCommandCandidates(base, platform)]);
for (const candidate of candidates) {
if (isWindowsHarnessShim(candidate)) continue;
const found = tryHarnessCommand(candidate, entry, runCommand, timeoutMs);
if (found) return found;
}
const inner = findWinNpmInnerExe(entry.id, {
platform,
pathEnv: probe.env?.PATH ?? process.env.PATH ?? "",
existsSync: probe.existsSync
});
if (inner) {
const found = tryHarnessCommand(inner, entry, runCommand, timeoutMs);
if (found) return found;
}
for (const candidate of candidates) {
if (!isWindowsHarnessShim(candidate)) continue;
const found = tryHarnessCommand(candidate, entry, runCommand, timeoutMs);
if (found) return found;
}
return void 0;
}
function probeEntry(entry, runCommand, timeoutMs, platform, probe = {}) {
const issues = [];
const found = detectHarnessCommand(entry, runCommand, timeoutMs, platform, probe);
const detected = Boolean(found);
const command = found?.command;
const version = found?.version;
let authenticated = null;
let authMethod;
if (!detected) authenticated = false;
else if (entry.id === "pi") {
authenticated = null;
issues.push("auth_context_required");
} else if (UNKNOWN_AUTH_HARNESSES.has(entry.id) || !entry.authArgs) {
authenticated = null;
if (UNKNOWN_AUTH_HARNESSES.has(entry.id)) issues.push("auth_unknown");
} else if (command) {
const parsed = interpretAuth(entry.id, runCommand(command, entry.authArgs, Math.max(timeoutMs, 1e4)));
authenticated = parsed.authenticated;
authMethod = parsed.authMethod;
issues.push(...parsed.issues);
}
if (command && isWindowsHarnessShim(command)) issues.push("windows_shim");
const dispatch = resolveDispatchStatus(entry, detected, authenticated, issues);
return {
id: entry.id,
label: entry.label,
default: entry.id === (probe.defaultHarness ?? DEFAULT_HARNESS),
mode: entry.mode,
detected,
authenticated,
...authMethod ? { authMethod } : {},
dispatch,
...command ? { command } : {},
...version ? { version } : {},
canUpdate: {
self: Boolean(entry.update.self.length),
extensions: Boolean(entry.update.extensions?.length),
models: Boolean(entry.update.models?.length)
},
issues
};
}
function probeHarnesses(options = {}) {
const timeoutMs = options.timeoutMs ?? 3e3;
const runCommand = options.runCommand ?? defaultRunner(options.env ?? process.env);
const platform = options.platform ?? process.platform;
return {
defaultHarness: options.defaultHarness ?? DEFAULT_HARNESS,
harnesses: BUILTIN_HARNESSES.map((entry) => probeEntry(entry, runCommand, timeoutMs, platform, options))
};
}
async function probeHarnessesAsync(options = {}) {
return replayHarnessProbe(
options.runCommand ?? defaultAsyncRunner(options.env ?? process.env, options.signal),
(runCommand) => probeHarnesses({ ...options, runCommand }),
256
);
}
function eligibleHarnesses(inventory) {
const eligible2 = inventory.harnesses.filter((entry) => entry !== void 0 && entry.detected && entry.authenticated === true).map((entry) => entry.id);
if (eligible2.length === 0) throw new Error("no_authenticated_harness");
return eligible2;
}
function validateHarnessModelPair(harnessId, modelSpec) {
if (!isKnownHarnessId(harnessId)) {
return { valid: false, issue: "harness_unknown", message: `unknown harness: ${harnessId}` };
}
let provider;
let model;
if (typeof modelSpec === "string") {
const trimmed = modelSpec.trim();
if (trimmed.includes("/")) {
const idx = trimmed.indexOf("/");
provider = trimmed.slice(0, idx).toLowerCase();
model = trimmed.slice(idx + 1);
} else {
model = trimmed;
}
} else {
provider = modelSpec.provider?.trim().toLowerCase();
model = modelSpec.model?.trim();
}
if (harnessId === "claude") {
if (provider && provider !== "anthropic") {
return { valid: false, issue: "harness_unhosted_model", message: `harness claude does not host provider ${provider}` };
}
if (model && /^(gpt|o1|o3|grok|gemini|kimi|moonshot|deepseek|qwen)-/i.test(model)) {
return { valid: false, issue: "harness_unhosted_model", message: `harness claude does not host model ${model}` };
}
return { valid: true };
}
if (harnessId === "codex") {
if (provider && provider !== "openai") {
return { valid: false, issue: "harness_unhosted_model", message: `harness codex does not host provider ${provider}` };
}
if (model && /^(claude|fable|grok|gemini|kimi|moonshot|deepseek|qwen)-/i.test(model)) {
return { valid: false, issue: "harness_unhosted_model", message: `harness codex does not host model ${model}` };
}
return { valid: true };
}
if (harnessId === "grok") {
if (provider && provider !== "xai") {
return { valid: false, issue: "harness_unhosted_model", message: `harness grok does not host provider ${provider}` };
}
if (model && !/^grok-/i.test(model)) {
return { valid: false, issue: "harness_unhosted_model", message: `harness grok only hosts grok models, received ${model}` };
}
return { valid: true };
}
if (harnessId === "agy") {
if (provider && provider !== "google") {
return { valid: false, issue: "harness_unhosted_model", message: `harness ${harnessId} does not host provider ${provider}` };
}
if (model && !/^gemini-/i.test(model)) {
return { valid: false, issue: "harness_unhosted_model", message: `harness ${harnessId} only hosts gemini models, received ${model}` };
}
return { valid: true };
}
if (harnessId === "kimi") {
if (provider && provider !== "moonshot") {
return { valid: false, issue: "harness_unhosted_model", message: `harness kimi does not host provider ${provider}` };
}
if (model && !/^(kimi|moonshot)(?:-|$)/i.test(model) && !/^kimi-for-coding(?:-|$)/i.test(model)) {
return { valid: false, issue: "harness_unhosted_model", message: `harness kimi only hosts kimi/moonshot models, received ${model}` };
}
return { valid: true };
}
if (harnessId === "deepseek") {
if (provider && provider !== "deepseek") {
return { valid: false, issue: "harness_unhosted_model", message: `harness deepseek does not host provider ${provider}` };
}
if (model && !/^deepseek-/i.test(model)) {
return { valid: false, issue: "harness_unhosted_model", message: `harness deepseek only hosts deepseek models, received ${model}` };
}
return { valid: true };
}
if (harnessId === "pi" || harnessId === "omp") {
if (!provider && model?.includes("/")) {
const idx = model.indexOf("/");
provider = model.slice(0, idx).toLowerCase();
model = model.slice(idx + 1);
}
if (!provider) return { valid: true };
const blocked = (message) => ({ valid: false, issue: "pi_native_impersonation_blocked", message });
if (PI_NATIVE_BRAKE_PROVIDERS.includes(provider)) {
return blocked(`${harnessId} must not impersonate native provider ${provider}; use the native harness`);
}
if (provider === "antigravity" && model && PI_ANTIGRAVITY_MODEL_ID.test(model)) return { valid: true };
const owned = Object.hasOwn(PI_VENDOR_OWNED_PROVIDERS, provider) ? PI_VENDOR_OWNED_PROVIDERS[provider] : void 0;
if (owned) {
return blocked(`${harnessId} provider ${provider} bills native vendor ${owned} for ${model ?? "this model"}; use the native harness`);
}
const segment = model?.includes("/") ? model.slice(0, model.indexOf("/")).toLowerCase() : void 0;
const vendor = segment && Object.hasOwn(PI_VENDOR_SEGMENT_ALIASES, segment) ? PI_VENDOR_SEGMENT_ALIASES[segment] : segment;
if (vendor && PI_NATIVE_BRAKE_PROVIDERS.includes(vendor)) {
return blocked(`${harnessId} must not bill native vendor ${vendor} through ${provider}; use the native harness`);
}
return { valid: true };
}
return { valid: true };
}
function probeHarnessAssignment(options) {
const timeoutMs = options.timeoutMs ?? 3e3;
const runCommand = options.runCommand ?? defaultRunner(options.env ?? process.env);
const platform = options.platform ?? process.platform;
const entry = BUILTIN_HARNESSES.find((candidate) => candidate.id === options.harness);
if (!entry) {
return {
id: options.harness,
label: options.harness,
default: false,
mode: "either",
detected: false,
authenticated: false,
dispatch: { status: "no", supported: false, reason: "harness_unknown" },
canUpdate: { self: false, extensions: false, models: false },
issues: ["harness_unknown"]
};
}
if (options.provider || options.model) {
const validation = validateHarnessModelPair(options.harness, { provider: options.provider, model: options.model });
if (!validation.valid) {
return {
id: entry.id,
label: entry.label,
default: entry.default,
mode: entry.mode,
detected: false,
authenticated: false,
dispatch: { status: "no", supported: false, reason: validation.issue ?? "harness_unhosted_model" },
canUpdate: {
self: Boolean(entry.update.self.length),
extensions: Boolean(entry.update.extensions?.length),
models: Boolean(entry.update.models?.length)
},
issues: [validation.issue ?? "harness_unhosted_model"]
};
}
}
const found = detectHarnessCommand(entry, runCommand, timeoutMs, platform, options);
const detected = Boolean(found);
const command = found?.command;
const version = found?.version;
const shimIssue = command && isWindowsHarnessShim(command) ? ["windows_shim"] : [];
if (!detected || !command) {
return {
id: entry.id,
label: entry.label,
default: entry.default,
mode: entry.mode,
detected: false,
authenticated: false,
dispatch: { status: "no", supported: false, reason: "not_detected" },
canUpdate: {
self: Boolean(entry.update.self.length),
extensions: Boolean(entry.update.extensions?.length),
models: Boolean(entry.update.models?.length)
},
issues: []
};
}
if (entry.id === "pi") {
if (!options.provider && !options.model) {
return {
id: entry.id,
label: entry.label,
default: entry.default,
mode: entry.mode,
detected: true,
authenticated: null,
dispatch: { status: "no", supported: false, reason: "auth_context_required" },
command,
...version ? { version } : {},
canUpdate: {
self: Boolean(entry.update.self.length),
extensions: Boolean(entry.update.extensions?.length),
models: Boolean(entry.update.models?.length)
},
issues: ["auth_context_required", ...shimIssue]
};
}
const authArgs = ["auth", "check"];
const qualifiedModel = options.model ? options.provider && options.model.startsWith(`${options.provider}/`) ? options.model : options.provider ? `${options.provider}/${options.model}` : options.model : void 0;
if (qualifiedModel) {
authArgs.push("--model", qualifiedModel);
} else if (options.provider) {
authArgs.push("--provider", options.provider);
}
authArgs.push("--json");
const result = runCommand(command, authArgs, timeoutMs);
const parsed = parseJsonObject(result.stdout);
let authenticated = false;
const issues = [];
if (result.error) {
issues.push("auth_probe_error");
} else if (parsed && parsed.status === "ready") {
authenticated = true;
} else if (parsed && parsed.status === "not_ready") {
authenticated = false;
issues.push("not_authenticated");
} else if (commandSucceeded(result) && /\bready\b/i.test(`${result.stdout}
${result.stderr}`)) {
authenticated = true;
} else {
authenticated = false;
issues.push("not_authenticated");
}
issues.push(...shimIssue);
const dispatch = resolveDispatchStatus(entry, true, authenticated, issues);
return {
id: entry.id,
label: entry.label,
default: entry.default,
mode: entry.mode,
detected: true,
authenticated,
dispatch,
command,
...version ? { version } : {},
canUpdate: {
self: Boolean(entry.update.self.length),
extensions: Boolean(entry.update.extensions?.length),
models: Boolean(entry.update.models?.length)
},
issues
};
}
return probeEntry(entry, runCommand, timeoutMs, platform);
}
var PendingHarnessCommand = class {
command;
args;
timeoutMs;
key;
constructor(command, args, timeoutMs, key) {
this.command = command;
this.args = [...args];
this.timeoutMs = timeoutMs;
this.key = key;
}
};
async function replayHarnessProbe(run, execute, limit) {
const observed = /* @__PURE__ */ new Map();
for (let commands = 0; commands <= limit; commands++) {
try {
return execute((command, args, timeoutMs) => {
const key = JSON.stringify([command, args, timeoutMs]);
const result = observed.get(key);
if (result) return result;
throw new PendingHarnessCommand(command, args, timeoutMs, key);
});
} catch (pending) {
if (!(pending instanceof PendingHarnessCommand)) throw pending;
if (commands === limit) throw new Error("auth_probe_command_limit");
observed.set(pending.key, await run(pending.command, pending.args, pending.timeoutMs));
}
}
throw new Error("auth_probe_command_limit");
}
async function probeHarnessAssignmentAsync(options) {
return replayHarnessProbe(
options.runCommand ?? defaultAsyncRunner(options.env ?? process.env, options.signal),
(runCommand) => probeHarnessAssignment({ ...options, runCommand }),
32
);
}
function probeHarnessesForModel(modelSpec, options = {}) {
const timeoutMs = options.timeoutMs ?? 3e3;
const runCommand = options.runCommand ?? defaultRunner(options.env ?? process.env);
const platform = options.platform ?? process.platform;
return {
defaultHarness: DEFAULT_HARNESS,
harnesses: BUILTIN_HARNESSES.map(
(entry) => probeHarnessAssignment({
harness: entry.id,
provider: modelSpec.provider,
model: modelSpec.model,
runCommand,
timeoutMs,
platform,
env: options.env,
existsSync: options.existsSync
})
)
};
}
async function probeHarnessesForModelAsync(modelSpec, options = {}) {
return replayHarnessProbe(
options.runCommand ?? defaultAsyncRunner(options.env ?? process.env, options.signal),
(runCommand) => probeHarnessesForModel(modelSpec, { ...options, runCommand }),
256
);
}
function scopesFor(scope, entry) {
if (scope === "self") return ["self"];
if (scope === "extensions") return entry.update.extensions ? ["extensions"] : [];
if (scope === "models") return entry.update.models ? ["models"] : [];
return [
...entry.update.self.length ? ["self"] : [],
...entry.update.extensions ? ["extensions"] : [],
...entry.update.models ? ["models"] : []
];
}
function argsFor(entry, scope) {
if (scope === "self") return entry.update.self;
if (scope === "extensions") return entry.update.extensions;
return entry.update.models;
}
function detectedHarnesses(inventory, requestedHarness) {
if (requestedHarness) return inventory.harnesses.filter((entry) => entry.id === requestedHarness);
const detected = inventory.harnesses.filter((entry) => entry.detected);
const preferred = inventory.defaultHarness;
return [
...detected.filter((entry) => entry.id === preferred),
...detected.filter((entry) => entry.id !== preferred)
];
}
function planHarnessUpdate(inventory, requested) {
const selected = detectedHarnesses(inventory, requested.harness);
if (requested.harness && selected.length === 0) {
return [{
harness: requested.harness,
scope: "self",
command: requested.harness,
args: [],
outcome: "skipped",
detail: isKnownHarnessId(requested.harness) ? "not_detected" : "unknown_harness"
}];
}
const waves = requested.scope === "all" ? ["self", "extensions", "models"] : [requested.scope];
const steps = [];
for (const scope of waves) {
for (const status of selected) {
const entry = BUILTIN_HARNESSES.find((candidate) => candidate.id === status.id);
if (!entry) continue;
const supported = scopesFor(requested.scope === "all" ? "all" : scope, entry);
if (!supported.includes(scope)) {
if (requested.scope !== "all") {
steps.push({
harness: status.id,
scope,
command: status.command ?? entry.commands[0],
args: [],
outcome: "skipped",
detail: "no_updater"
});
}
continue;
}
if (!status.detected || !status.command) {
steps.push({
harness: status.id,
scope,
command: entry.commands[0],
args: argsFor(entry, scope) ?? [],
outcome: "skipped",
detail: "not_detected"
});
continue;
}
steps.push({
harness: status.id,
scope,
command: status.command,
args: argsFor(entry, scope) ?? [],
outcome: "would"
});
}
}
return steps;
}
function runHarnessUpdate(steps, options = {}) {
if (options.dryRun) return steps.map((step) => ({ ...step, outcome: step.outcome === "would" ? "would" : step.outcome }));
const timeoutMs = options.updateTimeoutMs ?? 18e4;
const runCommand = options.runCommand ?? defaultRunner(options.env ?? process.env);
return steps.map((step) => {
if (step.outcome !== "would") return step;
const result = runCommand(step.command, step.args, timeoutMs);
const detail = boundText(result.stderr) ?? boundText(result.stdout) ?? result.error;
return {
...step,
outcome: result.ok ? "passed" : "failed",
...result.code !== void 0 && result.code !== null ? { code: result.code } : {},
...detail ? { detail } : {}
};
});
}
function formatHarnessInventory(inventory) {
const header = [
"id".padEnd(9),
"default".padEnd(8),
"detected".padEnd(9),
"auth".padEnd(8),
"dispatch".padEnd(26),
"updates"
].join(" ");
const rows = inventory.harnesses.map((entry) => {
const auth = entry.authenticated === true ? "yes" : entry.authenticated === false ? "no" : "unknown";
const dispatchText = entry.dispatch ? entry.dispatch.status === "yes" ? "yes" : `no (${entry.dispatch.reason ?? "unsupported"})` : entry.authenticated === true ? "yes" : "no";
const updates = [
entry.canUpdate.self ? "self" : void 0,
entry.canUpdate.extensions ? "extensions" : void 0,
entry.canUpdate.models ? "models" : void 0
].filter(Boolean).join(",") || "none";
const apiKeyNote = entry.issues.includes("auth_api_key") ? " API key" : "";
return [
entry.id.padEnd(9),
(entry.default ? "yes" : "no").padEnd(8),
(entry.detected ? "yes" : "no").padEnd(9),
auth.padEnd(8),
dispatchText.padEnd(26),
`${updates}${apiKeyNote}`
].join(" ");
});
return [
`default harness: ${inventory.defaultHarness} (used when an agent omits harness:)`,
"enable/disable = Git YAML (.kxm/agents, .kxm/models) or the harness's own plugin CLI",
"governed kxm skills are not auto-updated",
header,
...rows
].join("\n");
}
function formatHarnessUpdate(steps) {
if (steps.length === 0) return "nothing to update";
return steps.map((step) => {
const argv = [step.command, ...step.args].join(" ");
const detail = step.detail ? ` (${step.detail})` : "";
return `${step.harness} ${step.scope}: ${step.outcome} ${argv}${detail}`;
}).join("\n");
}
// plugins/kxm/src/project-config.ts
var KxmConfigError = class extends Error {
issues;
constructor(issues) {
const sorted = sortIssues3(issues);
super(sorted.map((issue4) => `${issue4.file}: ${issue4.code}: ${issue4.message}`).join("\n"));
this.name = "KxmConfigError";
this.issues = sorted;
}
};
function defaultKxmSchemaDir() {
return join3(findKxmRepoRoot(import.meta.url), "schemas");
}
var DEFAULT_SCHEMA_DIR = defaultKxmSchemaDir();
var RESOURCE_SCHEMA = Object.freeze({
project: { identity: "kxm.project.v1", file: "project.schema.json" },
repository: { identity: "kxm.repository.v1", file: "repository.schema.json" },
agent: { identity: "kxm.agent.v1", file: "agent.schema.json" },
model: { identity: "kxm.model.v2", file: "model.schema.json" },
role: { identity: "kxm.role.v2", file: "role.schema.json" },
environment: { identity: "kxm.environment.v1", file: "environment.schema.json" },
workflow: { identity: "kxm.workflow.v1", file: "workflow.schema.json" },
"gate-registry": { identity: "kxm.gate-registry.v1", file: "gate-registry.schema.json" }
});
var IDENTIFIER2 = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/;
var WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$|clock\$)$/i;
var BUILTIN_EXECUTORS = ["local", "ssh", "exe-dev"];
var TOOL_PRESET_PROFILES = Object.freeze({
coordinator: "read-only",
"read-only": "read-only",
"workspace-writer": "edit",
"tests-writer": "edit"
});
var BUILTIN_TOOL_PRESETS = Object.keys(TOOL_PRESET_PROFILES);
function toolPresetProfile(preset) {
if (!Object.hasOwn(TOOL_PRESET_PROFILES, preset)) return void 0;
return TOOL_PRESET_PROFILES[preset];
}
function toolPresetExceedsRoleMessage(preset, roleId, rolePermission, rolePreset) {
const profile = toolPresetProfile(preset);
if (profile !== "edit") return void 0;
if (rolePermission === "read-only") {
return `tools.preset ${preset} exceeds role ${roleId} permission read-only`;
}
if (rolePreset !== void 0 && toolPresetProfile(rolePreset) === "read-only") {
return `tools.preset ${preset} exceeds role ${roleId} preset ${rolePreset}`;
}
return void 0;
}
var SECRET_VALUE_PATTERNS = [
/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/,
/\b(?:ghp|github_pat)_[A-Za-z0-9_]{20,}\b/,
/\bsk-[A-Za-z0-9_-]{20,}\b/,
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/,
/\bAKIA[A-Z0-9]{16}\b/,
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/
];
function compareCodeUnits4(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
function sortIssues3(issues) {
return [...issues].sort((left, right) => compareCodeUnits4(left.file, right.file) || compareCodeUnits4(left.phase, right.phase) || compareCodeUnits4(left.code, right.code) || compareCodeUnits4(left.message, right.message));
}
function issue3(phase, code, file, message) {
return { phase, code, file, message };
}
function fail2(phase, code, file, message) {
throw new KxmConfigError([issue3(phase, code, file, message)]);
}
function isJsonObject2(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function parseRestrictedYaml2(input, label = "<yaml>", limits = KXM_YAML_LIMITS) {
try {
return parseRestrictedYaml(input, label, limits);
} catch (error) {
if (error instanceof RestrictedYamlError) throw new KxmConfigError(error.issues);
throw error;
}
}
function readJsonObject(file) {
const parsed = JSON.parse(readFileSync2(file, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`${file} is not a JSON object`);
return parsed;
}
var KxmSchemaRegistry = class {
schemasDir;
ajv;
validators = /* @__PURE__ */ new Map();
localBindingsValidator;
templateProvenanceValidator;
initOperationValidator;
permissionDiffValidator;
runEventValidator;
driveReceiptValidator;
coordinatorValidator;
intakeMessageValidator;
syncEventValidator;
constructor(schemasDir = DEFAULT_SCHEMA_DIR) {
this.schemasDir = resolve(schemasDir);
this.ajv = new import__.Ajv2020({ allErrors: true, strict: true, strictRequired: false });
const common = readJsonObject(join3(this.schemasDir, "common.schema.json"));
this.ajv.addSchema(common);
for (const definition of Object.values(RESOURCE_SCHEMA)) {
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, definition.file)));
}
const localBindingsFile = "local-repository-bindings.schema.json";
const templateProvenanceFile = "template-provenance.schema.json";
const initOperationFile = "init-operation.schema.json";
const permissionDiffFile = "permission-diff.schema.json";
const runEventFile = "run-event.schema.json";
const driveReceiptFile = "drive-receipt.schema.json";
const coordinatorFile = "coordinator.schema.json";
const intakeMessageFile = "intake-message.schema.json";
const syncEventFile = "sync-event.schema.json";
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, localBindingsFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, templateProvenanceFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, initOperationFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, permissionDiffFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, runEventFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, driveReceiptFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, coordinatorFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, intakeMessageFile)));
this.ajv.addSchema(readJsonObject(join3(this.schemasDir, syncEventFile)));
for (const [kind, definition] of Object.entries(RESOURCE_SCHEMA)) {
const validator = this.ajv.getSchema(`https://schemas.kxm.dev/${definition.file}`);
if (!validator) throw new Error(`schema did not compile: ${definition.file}`);
this.validators.set(kind, validator);
}
const localBindingsValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${localBindingsFile}`);
const templateProvenanceValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${templateProvenanceFile}`);
const initOperationValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${initOperationFile}`);
const permissionDiffValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${permissionDiffFile}`);
const runEventValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${runEventFile}`);
const driveReceiptValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${driveReceiptFile}`);
const coordinatorValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${coordinatorFile}`);
const intakeMessageValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${intakeMessageFile}`);
const syncEventValidator = this.ajv.getSchema(`https://schemas.kxm.dev/${syncEventFile}`);
if (!localBindingsValidator) throw new Error(`schema did not compile: ${localBindingsFile}`);
if (!templateProvenanceValidator) throw new Error(`schema did not compile: ${templateProvenanceFile}`);
if (!initOperationValidator) throw new Error(`schema did not compile: ${initOperationFile}`);
if (!permissionDiffValidator) throw new Error(`schema did not compile: ${permissionDiffFile}`);
if (!runEventValidator) throw new Error(`schema did not compile: ${runEventFile}`);
if (!driveReceiptValidator) throw new Error(`schema did not compile: ${driveReceiptFile}`);
if (!coordinatorValidator) throw new Error(`schema did not compile: ${coordinatorFile}`);
if (!intakeMessageValidator) throw new Error(`schema did not compile: ${intakeMessageFile}`);
if (!syncEventValidator) throw new Error(`schema did not compile: ${syncEventFile}`);
this.localBindingsValidator = localBindingsValidator;
this.templateProvenanceValidator = templateProvenanceValidator;
this.initOperationValidator = initOperationValidator;
this.permissionDiffValidator = permissionDiffValidator;
this.runEventValidator = runEventValidator;
this.driveReceiptValidator = driveReceiptValidator;
this.coordinatorValidator = coordinatorValidator;
this.intakeMessageValidator = intakeMessageValidator;
this.syncEventValidator = syncEventValidator;
}
validate(kind, value, file) {
const definition = RESOURCE_SCHEMA[kind];
if (value.schema !== definition.identity) {
return [issue3("schema", "schema_identity_mismatch", file, `expected ${definition.identity}, received ${String(value.schema)}`)];
}
const validator = this.validators.get(kind);
if (!validator) throw new Error(`missing KXM validator for ${kind}`);
if (validator(value)) return [];
return (validator.errors ?? []).map((error) => schemaIssue(file, error));
}
validateLocalBindings(value, file) {
return this.validateAuxiliary(value, file, "kxm.local-repository-bindings.v1", this.localBindingsValidator);
}
validateTemplateProvenance(value, file) {
return this.validateAuxiliary(value, file, "kxm.template-provenance.v1", this.templateProvenanceValidator);
}
validateInitOperation(value, file) {
return this.validateAuxiliary(value, file, "kxm.init-operation.v1", this.initOperationValidator);
}
validatePermissionDiff(value, file) {
return this.validateAuxiliary(value, file, "kxm.permission-diff.v1", this.permissionDiffValidator);
}
validateDriveReceipt(value, file) {
return this.validateAuxiliary(value, file, "kxm.drive-receipt.v1", this.driveReceiptValidator);
}
validateAuxiliary(value, file, identity, validator) {
if (value.schema !== identity) {
return [issue3("schema", "schema_identity_mismatch", file, `expected ${identity}, received ${String(value.schema)}`)];
}
if (validator(value)) return [];
return (validator.errors ?? []).map((error) => schemaIssue(file, error));
}
};
var cachedRunEventRegistry;
function validateRunEvent(value, file) {
const registry = cachedRunEventRegistry ??= new KxmSchemaRegistry();
if (!registry.runEventValidator(value)) {
throw new KxmConfigError([issue3(
"schema",
"run_event_invalid",
file,
registry.ajv.errorsText(registry.runEventValidator.errors, { separator: "; " })
)]);
}
}
function syncEventSchemaErrors(value) {
const registry = cachedRunEventRegistry ??= new KxmSchemaRegistry();
if (registry.syncEventValidator(value)) return void 0;
return registry.ajv.errorsText(registry.syncEventValidator.errors, { separator: "; " });
}
function validateDriveReceipt(value, file) {
const registry = cachedRunEventRegistry ??= new KxmSchemaRegistry();
if (!value || typeof value !== "object" || Array.isArray(value) || value.schema !== "kxm.drive-receipt.v1") {
throw new KxmConfigError([issue3(
"schema",
"drive_receipt_invalid",
file,
"expected kxm.drive-receipt.v1"
)]);
}
if (!registry.driveReceiptValidator(value)) {
throw new KxmConfigError([issue3(
"schema",
"drive_receipt_invalid",
file,
registry.ajv.errorsText(registry.driveReceiptValidator.errors, { separator: "; " })
)]);
}
}
function validateCoordinator(value, file) {
const registry = cachedRunEventRegistry ??= new KxmSchemaRegistry();
if (!value || typeof value !== "object" || Array.isArray(value) || value.schema !== "kxm.coordinator.v1") {
throw new KxmConfigError([issue3("schema", "coordinator_invalid", file, "expected kxm.coordinator.v1")]);
}
if (!registry.coordinatorValidator(value)) {
throw new KxmConfigError([issue3(
"schema",
"coordinator_invalid",
file,
registry.ajv.errorsText(registry.coordinatorValidator.errors, { separator: "; " })
)]);
}
}
function validateIntakeMessage(value, file) {
const registry = cachedRunEventRegistry ??= new KxmSchemaRegistry();
if (!value || typeof value !== "object" || Array.isArray(value) || value.schema !== "kxm.intake-message.v1") {
throw new KxmConfigError([issue3("schema", "intake_message_invalid", file, "expected kxm.intake-message.v1")]);
}
if (!registry.intakeMessageValidator(value)) {
throw new KxmConfigError([issue3(
"schema",
"intake_message_invalid",
file,
registry.ajv.errorsText(registry.intakeMessageValidator.errors, { separator: "; " })
)]);
}
}
function schemaIssue(file, error) {
const location = error.instancePath || "/";
const suffix = error.params && "additionalProperty" in error.params ? ` (${String(error.params.additionalProperty)})` : "";
return issue3("schema", `schema_${error.keyword}`, file, `${location} ${error.message ?? "is invalid"}${suffix}`);
}
function canonicalHostPath(path) {
const resolved = resolve(path);
try {
return realpathSync.native(resolved);
} catch {
return resolved;
}
}
function sameHostPath(left, right) {
const resolvedLeft = canonicalHostPath(left);
const resolvedRight = canonicalHostPath(right);
return process.platform === "win32" ? resolvedLeft.toLocaleLowerCase("en-US") === resolvedRight.toLocaleLowerCase("en-US") : resolvedLeft === resolvedRight;
}
function containedHostPath(root, candidate) {
const path = relative(root, candidate);
return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`);
}
function portableBindingIssue(root, pathHint, repositoryId) {
let current = root;
for (const segment of pathHint === "." ? [] : pathHint.split("/")) {
current = join3(current, segment);
if (!existsSync4(current)) break;
const stat = lstatSync(current);
if (stat.isSymbolicLink()) {
return issue3("path", "repository_binding_path_link", ".kxm/project.yaml", `portable pathHint for ${repositoryId} traverses a symbolic link or junction`);
}
}
const binding = resolve(root, ...pathHint.split("/"));
if (existsSync4(binding)) {
const realRoot = canonicalHostPath(root);
const realBinding = canonicalHostPath(binding);
if (!containedHostPath(realRoot, realBinding)) {
return issue3("path", "repository_binding_outside_project", ".kxm/project.yaml", `portable pathHint for ${repositoryId} resolves outside the authoritative project root`);
}
}
return void 0;
}
function kxmPortablePath(path) {
return portablePath(path);
}
function portablePath(path) {
if (path === ".") return true;
if (path.includes("\\") || path.startsWith("/") || /^[A-Za-z]:/.test(path) || /[<>:"|?*\u0000-\u001F]/.test(path)) return false;
const segments = path.split("/");
return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== ".." && !WINDOWS_RESERVED.test((segment.split(".")[0] ?? segment).replace(/[ .]+$/g, "")) && !segment.endsWith(".") && !segment.endsWith(" ") && !segment.includes(":"));
}
function kxmResourceIdentifier(id) {
return id.length <= 64 && IDENTIFIER2.test(id) && !WINDOWS_RESERVED.test(id);
}
function resourceIdentifier(id) {
return kxmResourceIdentifier(id);
}
function displayPath(root, file) {
const candidate = relative(root, file).replaceAll("\\", "/");
return candidate && !candidate.startsWith("../") ? candidate : file.replaceAll("\\", "/");
}
function readResource(registry, root, file, logicalPath, kind, id, containmentRoot = root) {
const label = displayPath(root, file);
let stat;
try {
stat = lstatSync(file);
} catch {
fail2("discovery", "resource_missing", label, "resource does not exist");
}
if (stat.isSymbolicLink()) fail2("path", "resource_symlink", label, "configuration resources must not be symbolic links");
const boundary = resolve(containmentRoot);
let parent = dirname2(file);
while (parent !== boundary) {
if (parent === dirname2(parent)) fail2("path", "resource_outside_project", label, "resource escapes the project root");
let parentStat;
try {
parentStat = lstatSync(parent);
} catch {
fail2("discovery", "resource_parent_missing", label, "resource parent does not exist");
}
if (parentStat.isSymbolicLink()) fail2("path", "resource_parent_symlink", label, "configuration resource parents must not be symbolic links");
parent = dirname2(parent);
}
if (!stat.isFile()) fail2("path", "resource_not_file", label, "configuration resource must be a regular file");
return { kind, ...id === void 0 ? {} : { id }, file, logicalPath, value: resourceValue(registry, readFileSync2(file), label, kind) };
}
function resourceValue(registry, input, label, kind) {
const value = parseRestrictedYaml2(input, label);
const issues = registry.validate(kind, value, label);
if (issues.length > 0) throw new KxmConfigError(issues);
return value;
}
function readTemplateProvenance(registry, root) {
const file = join3(root, ".kxm", "template-provenance.yaml");
if (!existsSync4(file)) return void 0;
const label = ".kxm/template-provenance.yaml";
const stat = lstatSync(file);
if (stat.isSymbolicLink() || !stat.isFile()) {
fail2("path", "resource_not_file", label, "template provenance must be a regular file, not a link or directory");
}
const configRoot = join3(root, ".kxm");
let parent = dirname2(file);
while (parent !== root) {
const parentStat = lstatSync(parent);
if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) {
fail2("path", "resource_parent_symlink", label, "template provenance parents must be regular directories");
}
if (parent === configRoot) break;
parent = dirname2(parent);
}
const value = parseRestrictedYaml2(readFileSync2(file), label);
const issues = registry.validateTemplateProvenance(value, label);
if (issues.length > 0) throw new KxmConfigError(issues);
if (!resolveKxmTemplateBaseline(value)) {
fail2("semantic", "template_provenance_revision_invalid", label, "template provenance does not exactly match a supported built-in baseline");
}
const files = Array.isArray(value.files) ? value.files : [];
const seen = /* @__PURE__ */ new Set();
let prior = "";
let managedBytes = 0;
for (const candidate of files) {
const record2 = objectValue(candidate);
const path = record2 && stringValue(record2.path);
if (!path) continue;
managedBytes += typeof record2.bytes === "number" ? record2.bytes : 0;
const folded = path.toLocaleLowerCase("en-US");
if (!path.startsWith(".kxm/") || path === label || !portablePath(path)) {
fail2("path", "template_provenance_path_invalid", label, `managed path ${path} is not a portable project-configuration path`);
}
if (seen.has(folded)) fail2("path", "template_provenance_path_collision", label, `managed path ${path} collides after case folding`);
if (prior && compareCodeUnits4(prior, path) >= 0) fail2("semantic", "template_provenance_order_invalid", label, "managed file entries must use strict code-unit order");
seen.add(folded);
prior = path;
}
if (managedBytes > 8 * 1024 * 1024) {
fail2("parse", "template_provenance_bounds_exceeded", label, "managed template manifest exceeds 8388608 bytes");
}
return value;
}
function listNamedResources(registry, root, directory, logicalDirectory, kind, replacedId, collected) {
const resources = /* @__PURE__ */ new Map();
if (!existsSync4(directory)) return resources;
const stat = lstatSync(directory);
if (stat.isSymbolicLink() || !stat.isDirectory()) {
fail2("path", "resource_directory_invalid", displayPath(root, directory), "resource directory must be a regular directory");
}
const issues = [];
const entries = readdirSync2(directory, { withFileTypes: true }).sort((left, right) => compareCodeUnits4(left.name, right.name));
for (const entry of entries) {
if (entry.isDirectory()) {
issues.push(issue3("path", "nested_resource_directory", displayPath(root, join3(directory, entry.name)), "nested resource directories are not allowed"));
continue;
}
if (!entry.name.toLowerCase().endsWith(".yaml") && !entry.name.toLowerCase().endsWith(".yml")) continue;
if (!entry.isFile() || extname(entry.name) !== ".yaml") {
issues.push(issue3("path", "resource_filename_invalid", displayPath(root, join3(directory, entry.name)), "resource must be a regular file with the exact .yaml extension"));
continue;
}
const id = basename(entry.name, ".yaml");
if (kind === "model" && id === "inventory") continue;
if (id === replacedId) continue;
if (!resourceIdentifier(id)) {
issues.push(issue3("path", "resource_id_invalid", displayPath(root, join3(directory, entry.name)), `filename-derived identity ${id} is invalid or platform-reserved`));
continue;
}
const collision = [...resources.keys()].find((candidate) => candidate.toLocaleLowerCase("en-US") === id.toLocaleLowerCase("en-US"));
if (collision) {
issues.push(issue3("path", "resource_id_collision", displayPath(root, join3(directory, entry.name)), `${id} case-folds to existing ${collision}`));
continue;
}
try {
const resource = readResource(registry, root, join3(directory, entry.name), `${logicalDirectory}/${id}.yaml`, kind, id);
resources.set(id, resource);
} catch (error) {
if (error instanceof KxmConfigError) issues.push(...error.issues);
else throw error;
}
}
if (issues.length > 0) {
if (collected) collected.push(...issues);
else throw new KxmConfigError(issues);
}
return resources;
}
function valuesOf(object, field) {
const value = object[field];
return Array.isArray(value) ? value : [];
}
function objectValue(value) {
return value !== void 0 && isJsonObject2(value) ? value : void 0;
}
function stringValue(value) {
return typeof value === "string" ? value : void 0;
}
function roleById(roles, roleId) {
const direct = roles.get(roleId);
if (direct) return direct;
const folded = roleId.toLocaleLowerCase("en-US");
for (const role of roles.values()) {
if ((role.id ?? "").toLocaleLowerCase("en-US") === folded) return role;
}
return void 0;
}
function numberValue(value, fallback) {
return typeof value === "number" ? value : fallback;
}
function names(value) {
return Array.isArray(value) ? value.filter((candidate) => typeof candidate === "string") : [];
}
function lookupKxmResource(resources, requested, kind) {
const records = [...resources].map((resource) => ({
id: resource.id,
aliases: names(resource.value.aliases),
resource
}));
return lookupById(records, requested, kind)?.record.resource;
}
function mapResource(resource, map, issues) {
const id = resource.id;
if (!id) return;
const collision = [...map.keys()].find((candidate) => candidate.toLocaleLowerCase("en-US") === id.toLocaleLowerCase("en-US"));
if (collision) {
issues.push(issue3("path", "resource_id_collision", resource.logicalPath, `${id} case-folds to existing ${collision}`));
return;
}
map.set(id, resource);
}
function validatePortablePaths(resource, issues) {
const candidates = [];
if (resource.kind === "project") {
for (const candidate of valuesOf(resource.value, "repositories")) {
const entry = objectValue(candidate);
const pathHint = entry && stringValue(entry.pathHint);
if (pathHint) candidates.push({ path: pathHint, label: "repositories[].pathHint" });
}
}
if (resource.kind === "environment") {
const path = objectValue(resource.value.path);
if (path) {
for (const field of ["prepend", "append"]) {
for (const candidate of names(path[field])) candidates.push({ path: candidate, label: `path.${field}[]` });
}
}
}
for (const candidate of candidates) {
if (!portablePath(candidate.path)) {
issues.push(issue3("path", "portable_path_invalid", resource.logicalPath, `${candidate.label} is not a normalized forward-slash relative path: ${candidate.path}`));
}
}
}
function selectorCandidates(selectorValue, models, file, label, issues) {
const selector = objectValue(selectorValue);
if (!selector) return [];
const profile = stringValue(selector.profile);
if (profile) {
const model = models.get(profile);
if (!model) issues.push(issue3("reference", "model_profile_unknown", file, `${label} references unknown model profile ${profile}`));
return model ? [model] : [];
}
const tag = stringValue(selector.tag);
if (!tag) return [];
const capabilities = new Set(names(selector.capabilities));
const candidates = [...models.values()].filter((model) => names(model.value.tags).includes(tag) && [...capabilities].every((capability) => names(model.value.capabilities).includes(capability)));
if (candidates.length === 0) issues.push(issue3("reference", "model_tag_unresolved", file, `${label} selector tag ${tag} has no matching profile`));
return candidates;
}
function modelCandidates(selectorValue, models) {
const selector = objectValue(selectorValue);
if (!selector) return [];
const profile = stringValue(selector.profile);
if (profile) {
const resource = models.get(profile);
if (!resource) return [];
return [{
key: `profile:${profile}`,
profile,
...stringValue(resource.value.provider) || stringValue(resource.value.vendor) ? { provider: stringValue(resource.value.provider) ?? stringValue(resource.value.vendor) } : {},
...stringValue(resource.value.model) ? { model: stringValue(resource.value.model) } : {}
}];
}
const tag = stringValue(selector.tag);
if (tag) {
const capabilities = new Set(names(selector.capabilities));
return [...models.values()].filter((resource) => names(resource.value.tags).includes(tag) && [...capabilities].every((capability) => names(resource.value.capabilities).includes(capability))).map((resource) => ({
key: `profile:${resource.id ?? "unknown"}`,
...resource.id ? { profile: resource.id } : {},
...stringValue(resource.value.provider) || stringValue(resource.value.vendor) ? { provider: stringValue(resource.value.provider) ?? stringValue(resource.value.vendor) } : {},
...stringValue(resource.value.model) ? { model: stringValue(resource.value.model) } : {}
}));
}
const provider = stringValue(selector.provider);
const model = stringValue(selector.model);
return provider && model ? [{ key: `direct:${provider}/${model}`, provider, model }] : [];
}
function compatibleModel(left, right) {
if (left.profile && right.profile) return left.profile === right.profile;
return left.provider === right.provider && left.model === right.model;
}
function diversityCandidates(stepSelector, allowedAgents, agents, models) {
const stepCandidates = modelCandidates(stepSelector, models);
const resolved = [];
for (const agentId of allowedAgents) {
const agentSelector = agents.get(agentId)?.value.model;
const agentCandidates = modelCandidates(agentSelector, models);
if (stepSelector === void 0) resolved.push(...agentCandidates);
else if (agentSelector === void 0) resolved.push(...stepCandidates);
else resolved.push(...stepCandidates.filter((candidate) => agentCandidates.some((allowed) => compatibleModel(candidate, allowed))));
}
if (allowedAgents.length === 0) resolved.push(...stepCandidates);
return [...new Map(resolved.map((candidate) => [candidate.key, candidate])).values()];
}
function validateEnvironment(resource, issues) {
const values = objectValue(resource.value.values) ?? {};
const secretNames = /* @__PURE__ */ new Set();
for (const candidate of valuesOf(resource.value, "secrets")) {
const secret = objectValue(candidate);
const name = secret && stringValue(secret.name);
if (!name) continue;
if (secretNames.has(name)) issues.push(issue3("semantic", "secret_name_duplicate", resource.logicalPath, `secret environment name ${name} is duplicated`));
secretNames.add(name);
if (Object.hasOwn(values, name)) issues.push(issue3("semantic", "environment_name_conflict", resource.logicalPath, `${name} appears in both values and secrets`));
}
for (const [name, value] of Object.entries(values)) {
if (typeof value === "string" && SECRET_VALUE_PATTERNS.some((pattern) => pattern.test(value))) {
issues.push(issue3("semantic", "probable_secret_value", resource.logicalPath, `${name} resembles a credential and must be represented by secrets[].ref`));
}
}
}
function accessRank(value) {
return value === "write" ? 2 : value === "read" ? 1 : 0;
}
function validateToolScope(agent, step, file, stepId, issues) {
const requested = objectValue(step.tools);
if (!requested) return;
const ceiling = objectValue(agent.value.tools);
if (!ceiling) {
issues.push(issue3("semantic", "tool_scope_expansion", file, `${stepId} requests tools but agent ${agent.id ?? "unknown"} declares no tool ceiling`));
return;
}
const requestedPreset = stringValue(requested.preset);
const ceilingPreset = stringValue(ceiling.preset);
if (requestedPreset !== ceilingPreset) {
issues.push(issue3("semantic", "tool_scope_expansion", file, `${stepId} tool preset ${String(requestedPreset)} does not preserve agent ${agent.id ?? "unknown"} preset ${String(ceilingPreset)}`));
}
const allowed = new Set(names(ceiling.allow));
const denied = new Set(names(ceiling.deny));
for (const tool of names(requested.allow)) {
if (!allowed.has(tool) || denied.has(tool)) issues.push(issue3("semantic", "tool_scope_expansion", file, `${stepId} requests tool ${tool} beyond agent ${agent.id ?? "unknown"} explicit allowlist`));
}
const requestedDenied = new Set(names(requested.deny));
for (const tool of denied) {
if (!requestedDenied.has(tool)) issues.push(issue3("semantic", "tool_scope_expansion", file, `${stepId} drops agent ${agent.id ?? "unknown"} denial for ${tool}`));
}
}
function validateToolPolicy(resource, policy, label, issues) {
if (!policy) return;
const allowed = new Set(names(policy.allow));
for (const tool of names(policy.deny)) {
if (allowed.has(tool)) issues.push(issue3("semantic", "tool_policy_contradiction", resource.logicalPath, `${label} both allows and denies ${tool}`));
}
}
function validateAgentScope(agent, step, repositories, file, stepId, issues) {
validateToolScope(agent, step, file, stepId, issues);
const agentRepositories = objectValue(agent.value.repositories) ?? {};
const defaultAccess = agent.value.defaultRepositoryAccess;
for (const [repositoryId, requested] of Object.entries(objectValue(step.repositories) ?? {})) {
if (!repositories.has(repositoryId)) continue;
const ceiling = agentRepositories[repositoryId] ?? defaultAccess ?? "none";
if (accessRank(requested) > accessRank(ceiling)) {
issues.push(issue3("semantic", "repository_scope_expansion", file, `${stepId} requests ${String(requested)} access to ${repositoryId} beyond agent ${agent.id ?? "unknown"} ceiling ${String(ceiling)}`));
}
}
const grants = new Set(valuesOf(agent.value, "secrets").map((candidate) => objectValue(candidate)).filter((candidate) => Boolean(candidate)).map((candidate) => stringValue(candidate.ref)).filter((candidate) => Boolean(candidate)));
for (const candidate of valuesOf(step, "secrets")) {
const reference = stringValue(objectValue(candidate)?.ref);
if (reference && !grants.has(reference)) {
issues.push(issue3("semantic", "secret_scope_expansion", file, `${stepId} requests secret ${reference} beyond agent ${agent.id ?? "unknown"} ceiling`));
}
}
}
var GATE_STEP_OUTCOMES = {
pass: ["passed", "implementation-failure"],
fail: ["passed", "repro-missing"]
};
function gateOutcomeImpossible(step, stepId, file) {
const expect = step.expect === "fail" ? "fail" : "pass";
const produced = GATE_STEP_OUTCOMES[expect];
const declared = Object.keys(objectValue(step.on) ?? {});
const impossible = declared.filter((outcome) => !produced.includes(outcome) && outcome !== "implementation_failure" && outcome !== "repro_missing");
const missing = produced.filter((outcome) => !declared.includes(outcome));
if (impossible.length === 0 || missing.length === 0) return void 0;
return issue3("semantic", "gate_outcome_impossible", file, `${stepId} declares ${impossible.join(", ")}, which a gate step with expect ${expect} never produces; it settles on ${produced.join(" or ")}, so declare ${missing.join(" and ")}`);
}
function transition(value) {
if (typeof value === "string") return { target: value };
const object = objectValue(value);
const target = stringValue(object?.target);
const terminalStatus = stringValue(object?.terminalStatus);
return {
...target === void 0 ? {} : { target },
...typeof object?.maxTransitions === "number" ? { maxTransitions: object.maxTransitions } : {},
...terminalStatus === void 0 ? {} : { terminalStatus }
};
}
function validateWorkflow(workflow, agents, models, repositories, gates, issues) {
const file = workflow.logicalPath;
const coordinator = stringValue(workflow.value.coordinator) ?? "coordinator";
if (!lookupKxmResource(agents.values(), coordinator, "agent")) issues.push(issue3("reference", "coordinator_unknown", file, `coordinator ${coordinator} does not exist`));
const steps = valuesOf(workflow.value, "steps").map((candidate) => objectValue(candidate)).filter((candidate) => Boolean(candidate));
const stepIndex = /* @__PURE__ */ new Map();
const primarySteps = /* @__PURE__ */ new Set();
for (const [index, step] of steps.entries()) {
const id = stringValue(step.id);
if (!id) continue;
if (stepIndex.has(id)) issues.push(issue3("semantic", "step_id_duplicate", file, `step ${id} is duplicated`));
else {
stepIndex.set(id, index);
primarySteps.add(id);
}
}
for (const [index, step] of steps.entries()) {
const id = stringValue(step.id);
if (!id) continue;
const aliases = new Set(names(step.aliases));
for (const [oldId, newId2] of STEP_RENAMES) {
if (id === newId2) aliases.add(oldId);
if (id === oldId) aliases.add(newId2);
}
for (const alias of aliases) {
if (alias === id || primarySteps.has(alias) || stepIndex.has(alias)) continue;
stepIndex.set(alias, index);
}
}
for (const field of ["reproOracle", "planHash"]) {
const oracle = objectValue(workflow.value[field]);
if (!oracle) continue;
const stageId = stringValue(oracle.stageId);
const evidenceKey = stringValue(oracle.evidenceKey);
const index = stageId === void 0 ? void 0 : stepIndex.get(stageId);
if (index === void 0) {
issues.push(issue3("reference", "oracle_stage_unknown", file, `${field} references unknown stage ${String(stageId)}`));
continue;
}
const evidence = new Set(valuesOf(steps[index] ?? {}, "requiredEvidence").map((candidate) => stringValue(objectValue(candidate)?.key)).filter((candidate) => Boolean(candidate)));
if (!evidenceKey || !evidence.has(evidenceKey)) issues.push(issue3("reference", "oracle_evidence_unknown", file, `${field} references undeclared evidence ${String(evidenceKey)} in ${stageId}`));
}
const planStages = new Set(names(workflow.value.requirePlanHash));
if (planStages.size > 0 && !objectValue(workflow.value.planHash)) issues.push(issue3("semantic", "plan_hash_missing", file, "requirePlanHash requires planHash"));
for (const stageId of planStages) {
if (!stepIndex.has(stageId)) issues.push(issue3("reference", "plan_hash_stage_unknown", file, `requirePlanHash references unknown stage ${stageId}`));
}
const adjacency = steps.map(() => /* @__PURE__ */ new Set());
const terminalReachable = /* @__PURE__ */ new Set();
const completedTerminalSources = /* @__PURE__ */ new Set();
let hasBackEdge = false;
for (const [index, step] of steps.entries()) {
const stepId = stringValue(step.id) ?? `step-${index}`;
const kind = stringValue(step.kind);
validateToolPolicy(workflow, objectValue(step.tools), `${stepId}.tools`, issues);
const primaryAgentId = stringValue(step.agent);
if ((kind === "agent" || kind === "moa") && primaryAgentId && !lookupKxmResource(agents.values(), primaryAgentId, "agent")) {
issues.push(issue3("reference", "agent_unknown", file, `${stepId} references unknown agent ${primaryAgentId}`));
}
const gate = stringValue(step.gate);
if (kind === "gate" && gate) {
if (!gates) issues.push(issue3("reference", "gate_registry_missing", file, `${stepId} requires .kxm/gates.yaml`));
else if (!gates.has(gate)) issues.push(issue3("reference", "gate_unknown", file, `${stepId} references unregistered gate ${gate}`));
}
if (step.expect !== void 0 && (kind !== "gate" || !["pass", "fail"].includes(String(step.expect)))) {
issues.push(issue3("semantic", "gate_expect_invalid", file, `${stepId} expect is gate-only pass or fail`));
}
if (kind === "gate" && Object.keys(objectValue(step.on) ?? {}).some((outcome) => outcome === "implementation_failure" || outcome === "repro_missing")) {
issues.push(issue3("semantic", "gate_outcome_renamed", file, `${stepId} must use implementation-failure and repro-missing`));
}
const impossibleOutcome = kind === "gate" ? gateOutcomeImpossible(step, stepId, file) : void 0;
if (impossibleOutcome) issues.push(impossibleOutcome);
for (const repositoryId of Object.keys(objectValue(step.repositories) ?? {})) {
if (!repositories.has(repositoryId)) issues.push(issue3("reference", "repository_unknown", file, `${stepId} references unknown repository ${repositoryId}`));
}
if ((kind === "agent" || kind === "moa") && step.model !== void 0) {
issues.push(issue3("semantic", "producer_route_unsupported", file, `${stepId} model is not honored; remove model from the step`));
}
selectorCandidates(step.model, models, file, `${stepId}.model`, issues);
const assignment = objectValue(step.assignments);
const declaredAgents = assignment ? names(assignment.allowedAgents) : [];
const allowedAgents = declaredAgents.length > 0 ? declaredAgents : primaryAgentId ? [primaryAgentId] : [];
for (const agentId of allowedAgents) {
const agent = lookupKxmResource(agents.values(), agentId, "agent");
if (!agent) issues.push(issue3("reference", "assignment_agent_unknown", file, `${stepId} allows unknown agent ${agentId}`));
else {
validateAgentScope(agent, step, repositories, file, stepId, issues);
if (step.model !== void 0 && agent.value.model !== void 0) {
const requestedModels = modelCandidates(step.model, models);
const ceilingModels = modelCandidates(agent.value.model, models);
const effectiveModels = requestedModels.filter((requested) => ceilingModels.some((ceiling) => compatibleModel(requested, ceiling)));
if (requestedModels.length > 0 && effectiveModels.length === 0) {
issues.push(issue3("semantic", "model_selector_incompatible", file, `${stepId} model selector has no candidate within agent ${agentId} ceiling`));
}
}
}
}
if (primaryAgentId && allowedAgents.length > 0 && !allowedAgents.includes(primaryAgentId)) {
issues.push(issue3("semantic", "primary_agent_ineligible", file, `${stepId} primary agent ${primaryAgentId} is not in allowedAgents`));
}
const minimum = numberValue(assignment?.minimum, 1);
const target = numberValue(assignment?.target, minimum);
const maximum = numberValue(assignment?.maximum, target);
const maxParallel = numberValue(assignment?.maxParallel, maximum);
if (!(minimum <= target && target <= maximum)) issues.push(issue3("semantic", "assignment_bounds_invalid", file, `${stepId} must satisfy minimum <= target <= maximum`));
if (maxParallel > maximum) issues.push(issue3("semantic", "assignment_parallelism_invalid", file, `${stepId} maxParallel exceeds maximum`));
if (assignment && allowedAgents.length > 0 && maximum > allowedAgents.length && kind === "moa") {
issues.push(issue3("semantic", "assignment_pool_too_small", file, `${stepId} maximum ${maximum} exceeds ${allowedAgents.length} eligible agents`));
}
const maxWriteRepositories = assignment && typeof assignment.maxWriteRepositories === "number" ? assignment.maxWriteRepositories : void 0;
if (maxWriteRepositories !== void 0) {
const writable = Object.values(objectValue(step.repositories) ?? {}).filter((access) => access === "write").length;
if (maxWriteRepositories > writable) issues.push(issue3("semantic", "write_repository_bound_invalid", file, `${stepId} maxWriteRepositories exceeds writable repository scope`));
}
const join27 = objectValue(step.join);
const minimumPassed = join27 && typeof join27.minimumPassed === "number" ? join27.minimumPassed : void 0;
if (minimumPassed !== void 0 && minimumPassed > maximum) issues.push(issue3("semantic", "join_impossible", file, `${stepId} minimumPassed exceeds assignment maximum`));
const distinctBy = names(assignment?.distinctBy);
if (distinctBy.length > 0) {
const candidates = diversityCandidates(step.model, allowedAgents, agents, models);
for (const dimension of distinctBy) {
const distinct = new Set(candidates.map((candidate) => candidate[dimension]).filter((value) => Boolean(value)));
if (distinct.size < target) issues.push(issue3("semantic", "model_diversity_impossible", file, `${stepId} requires ${target} distinct ${dimension} values but resolves ${distinct.size}`));
}
}
const evidenceKeys = /* @__PURE__ */ new Set();
for (const candidate of valuesOf(step, "requiredEvidence")) {
const requirement = objectValue(candidate);
if (!requirement) continue;
const key = stringValue(requirement.key);
if (key) {
if (evidenceKeys.has(key)) issues.push(issue3("semantic", "evidence_key_duplicate", file, `${stepId} evidence key ${key} is duplicated`));
evidenceKeys.add(key);
}
const policy = objectValue(requirement.producerPolicy);
if (!policy) continue;
const eligible2 = names(policy.eligibleAgents);
const producerMinimum = numberValue(policy.minimumProducers, 1);
if (producerMinimum > target || producerMinimum > eligible2.length) issues.push(issue3("semantic", "producer_minimum_impossible", file, `${stepId}.${String(key)} producer minimum exceeds its eligible or target pool`));
for (const agentId of eligible2) {
if (!lookupKxmResource(agents.values(), agentId, "agent")) issues.push(issue3("reference", "producer_agent_unknown", file, `${stepId}.${String(key)} references unknown producer ${agentId}`));
if (allowedAgents.length > 0 && !allowedAgents.includes(agentId)) issues.push(issue3("semantic", "producer_agent_ineligible", file, `${stepId}.${String(key)} producer ${agentId} is outside allowedAgents`));
}
const degradation = objectValue(policy.degradation);
if (degradation && numberValue(degradation.minimumProducers, 1) >= producerMinimum) issues.push(issue3("semantic", "producer_degradation_invalid", file, `${stepId}.${String(key)} degradation must lower minimumProducers`));
}
const writes = Object.values(objectValue(step.repositories) ?? {}).some((access) => access === "write");
const planHashStage = stringValue(objectValue(workflow.value.planHash)?.stageId);
const planHashIndex = planHashStage === void 0 ? void 0 : stepIndex.get(planHashStage);
if (writes && planHashIndex !== void 0 && index > planHashIndex && !planStages.has(stepId)) {
issues.push(issue3("semantic", "mutation_missing_plan_hash", file, `${stepId} mutates after the approved-plan stage but is absent from requirePlanHash`));
}
const outcomes = objectValue(step.on) ?? {};
if (Object.keys(outcomes).length === 0) issues.push(issue3("semantic", "step_transitions_missing", file, `${stepId} has no declared transitions`));
for (const [outcome, rawTransition] of Object.entries(outcomes)) {
const parsed = transition(rawTransition);
if (parsed.target === "$terminal") {
terminalReachable.add(index);
if (parsed.terminalStatus === "completed") completedTerminalSources.add(index);
continue;
}
if (parsed.target && parsed.target !== "$terminal" && !primarySteps.has(parsed.target) && stepIndex.has(parsed.target)) {
const canonical = stringValue(steps[stepIndex.get(parsed.target) ?? -1]?.id);
if (canonical) noteDeprecatedId("step", parsed.target, canonical);
}
const targetIndex = parsed.target === void 0 ? void 0 : stepIndex.get(parsed.target);
if (targetIndex === void 0) {
issues.push(issue3("reference", "transition_target_unknown", file, `${stepId}.${outcome} references unknown target ${String(parsed.target)}`));
continue;
}
adjacency[index]?.add(targetIndex);
if (targetIndex <= index) {
hasBackEdge = true;
if (parsed.maxTransitions === void 0) issues.push(issue3("semantic", "back_edge_unbounded", file, `${stepId}.${outcome} back-edge requires maxTransitions`));
}
}
}
if (hasBackEdge && typeof objectValue(workflow.value.limits)?.maxTransitions !== "number") {
issues.push(issue3("semantic", "workflow_cycle_unbounded", file, "workflow with back-edges requires limits.maxTransitions"));
}
const readyIndex = stepIndex.get("ready");
const verifyIndex = stepIndex.get("verify");
if (readyIndex !== void 0 && verifyIndex !== void 0) {
const verifyTargets = adjacency[verifyIndex] ?? /* @__PURE__ */ new Set();
if (!verifyTargets.has(readyIndex)) {
issues.push(issue3("semantic", "verify_must_precede_ready", file, "verify must transition to ready"));
}
for (const [srcIndex, targets] of adjacency.entries()) {
if (targets.has(readyIndex) && srcIndex !== verifyIndex) {
issues.push(issue3("semantic", "verify_must_precede_ready", file, `step ${String(steps[srcIndex]?.id)} transitions to ready bypassing verify`));
}
}
}
if (steps.length > 0) {
const reachable = /* @__PURE__ */ new Set([0]);
const queue = [0];
while (queue.length > 0) {
const current = queue.shift();
if (current === void 0) break;
for (const target of adjacency[current] ?? []) if (!reachable.has(target)) {
reachable.add(target);
queue.push(target);
}
}
for (const [index, step] of steps.entries()) if (!reachable.has(index)) issues.push(issue3("semantic", "step_unreachable", file, `step ${String(step.id)} is unreachable from the first step`));
for (const [requiredIndex, requiredStep] of steps.entries()) {
if (requiredStep.kind !== "gate" && requiredStep.kind !== "approval") continue;
const reachableWithoutRequired = /* @__PURE__ */ new Set();
const queueWithoutRequired = requiredIndex === 0 ? [] : [0];
if (requiredIndex !== 0) reachableWithoutRequired.add(0);
while (queueWithoutRequired.length > 0) {
const current = queueWithoutRequired.shift();
if (current === void 0) break;
for (const target of adjacency[current] ?? []) {
if (target === requiredIndex || reachableWithoutRequired.has(target)) continue;
reachableWithoutRequired.add(target);
queueWithoutRequired.push(target);
}
}
if ([...completedTerminalSources].some((source) => source !== requiredIndex && reachableWithoutRequired.has(source))) {
issues.push(issue3("semantic", "required_step_bypass", file, `a completed path can bypass required ${String(requiredStep.id)}`));
}
}
const canTerminate = new Set(terminalReachable);
let changed = true;
while (changed) {
changed = false;
for (const [index, targets] of adjacency.entries()) {
if (!canTerminate.has(index) && [...targets].some((target) => canTerminate.has(target))) {
canTerminate.add(index);
changed = true;
}
}
}
for (const index of reachable) if (!canTerminate.has(index)) issues.push(issue3("semantic", "step_cannot_terminate", file, `step ${String(steps[index]?.id)} has no path to a terminal transition`));
}
}
function validateModelReferences(models, issues) {
for (const model of models.values()) {
for (const [index, fallback] of valuesOf(model.value, "fallbacks").entries()) {
selectorCandidates(fallback, models, model.logicalPath, `fallbacks[${index}]`, issues);
}
}
const visiting = /* @__PURE__ */ new Set();
const visited = /* @__PURE__ */ new Set();
const walk = (id, path) => {
if (visiting.has(id)) {
issues.push(issue3("semantic", "model_fallback_cycle", models.get(id)?.logicalPath ?? ".kxm/models", `fallback profile cycle: ${[...path, id].join(" -> ")}`));
return;
}
if (visited.has(id)) return;
visiting.add(id);
const model = models.get(id);
if (model) {
for (const fallback of valuesOf(model.value, "fallbacks")) {
const profile = stringValue(objectValue(fallback)?.profile);
if (profile && models.has(profile)) walk(profile, [...path, id]);
}
}
visiting.delete(id);
visited.add(id);
};
for (const id of models.keys()) walk(id, []);
}
function validateBundle(project, repositories, agents, models, workflows, environments, options, gateRegistry, projectRoot, roles = /* @__PURE__ */ new Map()) {
const issues = [];
const entries = valuesOf(project.value, "repositories").map((candidate) => objectValue(candidate)).filter((candidate) => Boolean(candidate));
const repositoryIds = /* @__PURE__ */ new Set();
const foldedRepositories = /* @__PURE__ */ new Map();
let controls = 0;
for (const entry of entries) {
const id = stringValue(entry.id);
if (!id) continue;
const folded = id.toLocaleLowerCase("en-US");
const previous = foldedRepositories.get(folded);
if (previous) issues.push(issue3("path", "repository_id_collision", project.logicalPath, `${id} case-folds to existing ${previous}`));
else foldedRepositories.set(folded, id);
repositoryIds.add(id);
if (entry.role === "control") controls += 1;
}
if (controls !== 1) issues.push(issue3("semantic", "control_repository_count", project.logicalPath, `expected exactly one control repository, received ${controls}`));
for (const repository of repositories.values()) {
if (repository.value.projectId !== project.value.id) issues.push(issue3("reference", "repository_project_mismatch", repository.logicalPath, "projectId does not match the authoritative project"));
const id = stringValue(repository.value.repositoryId);
if (!id || !repositoryIds.has(id)) issues.push(issue3("reference", "repository_definition_unknown", repository.logicalPath, `repositoryId ${String(id)} is not bound by project.yaml`));
if (repository.id !== id) issues.push(issue3("reference", "repository_binding_identity_mismatch", repository.logicalPath, `binding ${String(repository.id)} declares repositoryId ${String(id)}`));
}
for (const resource of [project, ...environments]) validatePortablePaths(resource, issues);
for (const environment of environments) validateEnvironment(environment, issues);
const executors = new Set(options.registeredExecutors ?? BUILTIN_EXECUTORS);
const gates = gateRegistry ? new Set(Object.keys(objectValue(gateRegistry.value.gates) ?? {})) : void 0;
for (const [id, value] of Object.entries(objectValue(gateRegistry?.value.gates) ?? {})) {
const definition = objectValue(value);
const executable = Array.isArray(definition?.argv) ? definition.argv[0] : void 0;
if (definition?.kind === "command" && typeof executable === "string" && (executable === "." || executable === ".." || executable.includes("\\") || !executable.startsWith("/") && executable.includes("/"))) {
issues.push(issue3("semantic", "gate_executable_invalid", ".kxm/gates.yaml", `${id} argv[0] must be a bare executable or absolute POSIX path`));
}
}
const presets = new Set(options.registeredToolPresets ?? BUILTIN_TOOL_PRESETS);
const harnesses = new Set(options.registeredHarnesses ?? BUILTIN_HARNESS_IDS);
const defaultExecutor = stringValue(project.value.defaultExecutor);
if (defaultExecutor && !executors.has(defaultExecutor)) issues.push(issue3("reference", "executor_unknown", project.logicalPath, `defaultExecutor ${defaultExecutor} is not registered`));
const defaultHarness = stringValue(project.value.defaultHarness) ?? DEFAULT_HARNESS;
if (!harnesses.has(defaultHarness)) issues.push(issue3("reference", "harness_unknown", project.logicalPath, `defaultHarness ${defaultHarness} is not registered`));
for (const agent of agents.values()) {
if (agent.value.model !== void 0 || agent.value.harness !== void 0) {
issues.push(issue3("semantic", "retired_agent_routing_fields", agent.logicalPath, "routing resolves from role; remove model and harness"));
}
validateToolPolicy(agent, objectValue(agent.value.tools), "tools", issues);
const executor = stringValue(agent.value.executor);
if (executor && !executors.has(executor)) issues.push(issue3("reference", "executor_unknown", agent.logicalPath, `executor ${executor} is not registered`));
const preset = stringValue(objectValue(agent.value.tools)?.preset);
if (preset && !presets.has(preset)) issues.push(issue3("reference", "tool_preset_unknown", agent.logicalPath, `tool preset ${preset} is not registered`));
const roleId = stringValue(agent.value.role);
const role = roleId ? roleById(roles, roleId) : void 0;
const rolePermission = stringValue(role?.value.permission);
if (preset && role && (rolePermission === "edit" || rolePermission === "read-only")) {
const message = toolPresetExceedsRoleMessage(
preset,
role.id ?? roleId ?? "role",
rolePermission,
stringValue(objectValue(role.value.tools)?.preset)
);
if (message) issues.push(issue3("semantic", "tool_preset_exceeds_role", agent.logicalPath, message));
}
for (const repositoryId of Object.keys(objectValue(agent.value.repositories) ?? {})) {
if (!repositoryIds.has(repositoryId)) issues.push(issue3("reference", "repository_unknown", agent.logicalPath, `references unknown repository ${repositoryId}`));
}
}
for (const role of roles.values()) {
const permission = stringValue(role.value.permission);
const rolePreset = stringValue(objectValue(role.value.tools)?.preset);
if (permission === "read-only" && rolePreset && toolPresetProfile(rolePreset) === "edit") {
issues.push(issue3("semantic", "tool_preset_exceeds_role", role.logicalPath, `tools.preset ${rolePreset} exceeds permission read-only`));
}
}
validateModelReferences(models, issues);
const defaultWorkflow = stringValue(project.value.defaultWorkflow) ?? "default";
if (!lookupKxmResource(workflows.values(), defaultWorkflow, "workflow")) issues.push(issue3("reference", "default_workflow_unknown", project.logicalPath, `default workflow ${defaultWorkflow} does not exist`));
for (const workflow of workflows.values()) validateWorkflow(workflow, agents, models, repositoryIds, gates, issues);
if (projectRoot && existsSync4(join3(projectRoot, ".kxm", "roster.yaml"))) {
issues.push(issue3("semantic", "retired_roster_file", ".kxm/roster.yaml", "create the role and model files and delete roster.yaml"));
}
if (projectRoot && existsSync4(join3(projectRoot, ".kxm", "roles"))) {
issues.push(...developerRolePolicyIssues(projectRoot));
}
if (projectRoot) {
issues.push(...rosterModelIssues(projectRoot, roles));
issues.push(...originHashIssues(projectRoot, models));
}
return sortIssues3(issues);
}
function rosterModelIssues(projectRoot, roles) {
const issues = [];
for (const role of roles.values()) {
for (const entry of valuesOf(role.value, "roster")) {
const route = stringValue(objectValue(entry)?.route);
if (!route) continue;
const resolved = findYamlBasename(join3(projectRoot, ".kxm", "models"), route, "route") ?? route;
const logical = `.kxm/models/${resolved}.yaml`;
const file = join3(projectRoot, ".kxm", "models", `${resolved}.yaml`);
let harness;
try {
if (existsSync4(file)) harness = stringValue(parseRestrictedYaml2(readFileSync2(file, "utf8"), logical).harness);
} catch {
harness = void 0;
}
if (!harness) {
issues.push(issue3("semantic", "roster_model_unreadable", role.logicalPath, `roster route ${route} does not resolve to a readable ${logical} carrying harness`));
}
}
}
return issues;
}
function originHashIssues(projectRoot, models) {
const issues = [];
for (const model of models.values()) {
const origin = objectValue(model.value.origin);
const source = origin ? stringValue(origin.source) : void 0;
const digest2 = origin ? stringValue(origin.sha256) : void 0;
if (!source || !digest2) continue;
const file = resolve(projectRoot, source);
const escaped = relative(projectRoot, file);
if (isAbsolute(source) || escaped.startsWith("..") || isAbsolute(escaped)) {
issues.push(issue3("semantic", "origin_evidence_missing", model.logicalPath, `missing evidence bytes for ${source}`));
continue;
}
let actual;
try {
actual = createHash3("sha256").update(readFileSync2(file, "utf8"), "utf8").digest("hex");
} catch (error) {
const code = error.code;
if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EISDIR") {
issues.push(issue3("semantic", "origin_evidence_missing", model.logicalPath, `missing evidence bytes for ${source}`));
continue;
}
throw error;
}
if (actual !== digest2) {
issues.push(issue3("semantic", "origin_hash_mismatch", model.logicalPath, "origin evidence hash does not match supplied bytes"));
}
}
return issues;
}
function developerCeilings() {
const script = join3(findKxmRepoRoot(import.meta.url), "scripts", "harness-run.mjs");
let loaded;
try {
loaded = spawnSync2(process.execPath, ["--input-type=module", "-e", `const m = await import(${JSON.stringify(pathToFileURL(script).href)}); process.stdout.write(JSON.stringify({ROUTES:m.ROUTES,NATIVE_PI_BRAKE_PROVIDERS:m.NATIVE_PI_BRAKE_PROVIDERS,PI_ALLOWED_PROVIDERS:m.PI_ALLOWED_PROVIDERS,PI_NATIVE_VENDOR_PROVIDERS:m.PI_NATIVE_VENDOR_PROVIDERS}))`], {
encoding: "utf8",
timeout: 15e3
});
} catch (error) {
return { ok: false, detail: error instanceof Error ? error.message : String(error) };
}
if (loaded.error) {
const code = loaded.error.code;
const detail = code === "ETIMEDOUT" || loaded.signal ? `timed out after 15s (${loaded.error.message})` : loaded.error.message;
return { ok: false, detail };
}
if (loaded.status !== 0 || !loaded.stdout) {
const stderr = (loaded.stderr ?? "").trim();
return { ok: false, detail: stderr || `scripts/harness-run.mjs exited ${loaded.status}` };
}
try {
return { ok: true, ...JSON.parse(loaded.stdout) };
} catch (error) {
return { ok: false, detail: `ceilings JSON parse failed: ${error instanceof Error ? error.message : String(error)}` };
}
}
function developerRolePolicyIssues(projectRoot) {
if (resolve(projectRoot) !== findKxmRepoRoot(import.meta.url)) return [];
const lintIssues = lintWorkforce(projectRoot).errors.map((entry) => issue3("semantic", entry.code, entry.file, entry.message));
const rolesDir = join3(projectRoot, ".kxm", "roles");
const modelsDir = join3(projectRoot, ".kxm", "models");
const roles = {};
const models = {};
const evidence = {};
const parseIssues = [];
const readMap = (dir, into, skipInventory) => {
if (!existsSync4(dir)) return;
for (const name of readdirSync2(dir)) {
if (!name.endsWith(".yaml")) continue;
const id = basename(name, ".yaml");
if (skipInventory && id === "inventory") continue;
try {
const value = parseRestrictedYaml2(readFileSync2(join3(dir, name), "utf8"), `${dir}/${name}`);
into[id] = value;
} catch (error) {
if (error instanceof KxmConfigError) {
parseIssues.push(...error.issues);
continue;
}
throw error;
}
}
};
readMap(rolesDir, roles, false);
readMap(modelsDir, models, true);
for (const model of Object.values(models)) {
const origin = objectValue(model.origin);
const source = origin ? stringValue(origin.source) : void 0;
if (!source || evidence[source] !== void 0) continue;
const evidenceFile = isAbsolute(source) ? source : join3(projectRoot, source);
if (existsSync4(evidenceFile)) evidence[source] = readFileSync2(evidenceFile, "utf8");
}
const ceilings = developerCeilings();
if (!ceilings.ok) {
return [...parseIssues, ...lintIssues, issue3("semantic", "developer_ceilings_unavailable", ".kxm/models", `developer ceilings could not be loaded: ${ceilings.detail}`)];
}
const result = validatePolicyDraft({ models, roles, evidence }, {
ceilings: ceilings.ROUTES,
nativePiBrakeProviders: ceilings.NATIVE_PI_BRAKE_PROVIDERS,
piAllowedProviders: ceilings.PI_ALLOWED_PROVIDERS,
piNativeVendorProviders: ceilings.PI_NATIVE_VENDOR_PROVIDERS,
vendorAliases: { "x-ai": "xai", moonshotai: "moonshot", "google-ai": "google", qwen: "alibaba" }
});
if (result.ok) return [...parseIssues, ...lintIssues];
return [...parseIssues, ...lintIssues, ...result.issues.map((entry) => issue3(entry.phase, entry.code, entry.file, entry.message))];
}
function kxmCanonicalJson(value) {
if (value === null || typeof value !== "object") return JSON.stringify(value);
if (Array.isArray(value)) return `[${value.map((candidate) => kxmCanonicalJson(candidate)).join(",")}]`;
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${kxmCanonicalJson(value[key])}`).join(",")}}`;
}
function canonicalize(value) {
return kxmCanonicalJson(value);
}
function bundleRevision(resources) {
const hash = createHash3("sha256");
for (const resource of [...resources].sort((left, right) => compareCodeUnits4(left.logicalPath, right.logicalPath))) {
hash.update(resource.logicalPath, "utf8");
hash.update("\0", "utf8");
hash.update(canonicalize(resource.value), "utf8");
hash.update("\0", "utf8");
}
return `sha256:${hash.digest("hex")}`;
}
function gitEnvironment() {
return Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.toUpperCase().startsWith("GIT_")));
}
function discoverGitRoot(start = process.cwd()) {
let current = resolve(start);
if (existsSync4(current) && !lstatSync(current).isDirectory()) current = dirname2(current);
const result = spawnSync2("git", ["-C", current, "rev-parse", "--show-toplevel"], {
encoding: "utf8",
env: gitEnvironment(),
timeout: 5e3,
windowsHide: true
});
if (result.status !== 0 || result.error || !result.stdout.trim()) return void 0;
const root = resolve(result.stdout.trim());
return existsSync4(root) && lstatSync(root).isDirectory() ? root : void 0;
}
function assertNoRegisteredGates(options) {
if ("registeredGates" in options) {
throw new KxmConfigError([issue3("semantic", "registered_gates_removed", ".kxm/gates.yaml", "registeredGates was removed; declare gates in .kxm/gates.yaml")]);
}
}
function loadKxmProject(projectRoot, options = {}) {
return loadProjectBundle(projectRoot, options);
}
function loadProjectBundle(projectRoot, options, candidate) {
const workflowCandidate = candidate?.kind === "workflow" ? candidate : void 0;
const writerRole = candidate?.kind === "role" && candidate.id.toLocaleLowerCase("en-US") === "writer" ? candidate.document : void 0;
assertNoRegisteredGates(options);
const root = resolve(projectRoot);
const legacyPresent = legacyConfigFilesAt(root);
if (legacyPresent.length > 0) {
throw new KxmConfigError(legacyPresent.map((file) => issue3(
"semantic",
"legacy_state_unsupported",
file,
"legacy JSON configuration is present and this build does not migrate it: delete these files once their YAML replacements exist in .kxm/, or initialise a fresh project"
)));
}
const registry = new KxmSchemaRegistry(options.schemasDir);
const project = readResource(registry, root, join3(root, ".kxm", "project.yaml"), ".kxm/project.yaml", "project");
const earlyIssues = [];
validatePortablePaths(project, earlyIssues);
const templateProvenance = readTemplateProvenance(registry, root);
if (templateProvenance && templateProvenance.inputs && typeof templateProvenance.inputs === "object" && !Array.isArray(templateProvenance.inputs)) {
const provenanceProjectId = stringValue(templateProvenance.inputs.projectId);
if (provenanceProjectId !== stringValue(project.value.id)) {
earlyIssues.push(issue3("semantic", "template_provenance_project_mismatch", ".kxm/template-provenance.yaml", "template provenance belongs to a different project identity"));
}
}
const declaredRepositoryIds = new Set(valuesOf(project.value, "repositories").map((candidate2) => stringValue(objectValue(candidate2)?.id)).filter((candidate2) => candidate2 !== void 0));
for (const repositoryId of Object.keys(options.repositoryBindings ?? {}).sort(compareCodeUnits4)) {
if (!resourceIdentifier(repositoryId)) {
earlyIssues.push(issue3("path", "repository_binding_id_invalid", ".kxm/project.yaml", `host-local binding identity ${repositoryId} is invalid`));
} else if (!declaredRepositoryIds.has(repositoryId)) {
earlyIssues.push(issue3("reference", "repository_binding_unknown", ".kxm/project.yaml", `host-local binding references unknown repository ${repositoryId}`));
}
}
if (earlyIssues.length > 0) throw new KxmConfigError(earlyIssues);
const agents = listNamedResources(registry, root, join3(root, ".kxm", "agents"), ".kxm/agents", "agent");
const modelIssues = [];
const models = listNamedResources(registry, root, join3(root, ".kxm", "models"), ".kxm/models", "model", void 0, modelIssues);
const roles = listNamedResources(registry, root, join3(root, ".kxm", "roles"), ".kxm/roles", "role", writerRole === void 0 ? void 0 : "writer");
if (writerRole !== void 0) {
const logicalPath = ".kxm/roles/writer.yaml";
roles.set("writer", { kind: "role", id: "writer", file: join3(root, logicalPath), logicalPath, value: resourceValue(registry, writerRole, logicalPath, "role") });
}
const workflows = listNamedResources(registry, root, join3(root, ".kxm", "workflows"), ".kxm/workflows", "workflow", workflowCandidate?.id);
if (workflowCandidate) {
const { id, document } = workflowCandidate;
const logicalPath = `.kxm/workflows/${id}.yaml`;
if (!resourceIdentifier(id)) fail2("path", "resource_id_invalid", logicalPath, `filename-derived identity ${id} is invalid or platform-reserved`);
const collision = [...workflows.keys()].find((candidate2) => candidate2.toLocaleLowerCase("en-US") === id.toLocaleLowerCase("en-US"));
if (collision) fail2("path", "resource_id_collision", logicalPath, `${id} case-folds to existing ${collision}`);
workflows.set(id, { kind: "workflow", id, file: join3(root, logicalPath), logicalPath, value: resourceValue(registry, document, logicalPath, "workflow") });
}
const gatePath = join3(root, ".kxm", "gates.yaml");
const gateRegistry = existsSync4(gatePath) ? readResource(registry, root, gatePath, ".kxm/gates.yaml", "gate-registry") : void 0;
const environments = [];
const repositories = /* @__PURE__ */ new Map();
const loadIssues = [];
const projectEnvironment = join3(root, ".kxm", "project", "env.yaml");
if (existsSync4(projectEnvironment)) {
try {
environments.push(readResource(registry, root, projectEnvironment, ".kxm/project/env.yaml", "environment"));
} catch (error) {
if (error instanceof KxmConfigError) loadIssues.push(...error.issues);
else throw error;
}
}
const seenBindings = /* @__PURE__ */ new Map();
for (const candidate2 of valuesOf(project.value, "repositories")) {
const entry = objectValue(candidate2);
const repositoryId = entry && stringValue(entry.id);
const pathHint = entry && stringValue(entry.pathHint);
const role = entry && stringValue(entry.role);
const required2 = entry?.required !== false;
if (!repositoryId) continue;
const hasLocalBinding = Object.hasOwn(options.repositoryBindings ?? {}, repositoryId);
const localBinding = options.repositoryBindings?.[repositoryId];
if (hasLocalBinding && (!localBinding || !isAbsolute(localBinding))) {
loadIssues.push(issue3("path", "repository_binding_not_absolute", ".kxm/project.yaml", `host-local binding for ${repositoryId} must be absolute`));
continue;
}
if (role === "control" && localBinding && !sameHostPath(localBinding, root)) {
loadIssues.push(issue3("path", "control_repository_binding_invalid", ".kxm/project.yaml", `control repository ${repositoryId} must bind to the authoritative project root`));
continue;
}
if (role === "control" && pathHint !== void 0 && pathHint !== ".") {
loadIssues.push(issue3("path", "control_repository_path_invalid", ".kxm/project.yaml", `control repository ${repositoryId} must use pathHint .`));
continue;
}
if (!hasLocalBinding && role !== "control" && pathHint && portablePath(pathHint)) {
const pathIssue = portableBindingIssue(root, pathHint, repositoryId);
if (pathIssue) {
loadIssues.push(pathIssue);
continue;
}
}
const binding = hasLocalBinding && localBinding ? resolve(localBinding) : role === "control" ? root : pathHint && portablePath(pathHint) ? resolve(root, ...pathHint.split("/")) : void 0;
if (!binding) {
if (required2) loadIssues.push(issue3("discovery", "repository_binding_missing", ".kxm/project.yaml", `required repository ${repositoryId} has no portable pathHint or host-local binding`));
continue;
}
if (!existsSync4(binding)) {
if (required2 || hasLocalBinding) loadIssues.push(issue3("discovery", "repository_binding_unavailable", ".kxm/project.yaml", `${hasLocalBinding ? "explicit" : "required"} repository binding ${repositoryId} is unavailable`));
continue;
}
const bindingStat = lstatSync(binding);
if (bindingStat.isSymbolicLink() || !bindingStat.isDirectory()) {
loadIssues.push(issue3("path", "repository_binding_invalid", ".kxm/project.yaml", `repository binding ${repositoryId} must be a regular directory`));
continue;
}
if (role === "member") {
const repositoryGitRoot = discoverGitRoot(binding);
if (!repositoryGitRoot || !sameHostPath(repositoryGitRoot, binding)) {
loadIssues.push(issue3("discovery", "repository_git_root_invalid", ".kxm/project.yaml", `member repository ${repositoryId} must bind to its authoritative Git worktree root`));
continue;
}
}
const memberLegacy = binding === root ? [] : legacyConfigFilesAt(binding);
if (memberLegacy.length > 0) {
throw new KxmConfigError(memberLegacy.map((file) => issue3(
"semantic",
"legacy_state_unsupported",
`${repositoryId}/${file}`,
`repository ${repositoryId} holds legacy JSON configuration and this build does not migrate it: delete those files once their YAML replacements exist, or bind a clean worktree`
)));
}
const foldedBinding = canonicalHostPath(binding).toLocaleLowerCase("en-US");
const priorBinding = seenBindings.get(foldedBinding);
if (priorBinding && priorBinding !== repositoryId) {
loadIssues.push(issue3("path", "repository_binding_collision", ".kxm/project.yaml", `${repositoryId} and ${priorBinding} use the same repository binding`));
continue;
}
seenBindings.set(foldedBinding, repositoryId);
const repositoryFile = join3(binding, ".kxm", "repo", "repo.yaml");
let definitionValidated = false;
if (existsSync4(repositoryFile)) {
try {
const resource = readResource(registry, root, repositoryFile, `.kxm/repositories/${repositoryId}/repo.yaml`, "repository", repositoryId, binding);
if (resource.value.repositoryId !== repositoryId) {
loadIssues.push(issue3("reference", "repository_binding_identity_mismatch", resource.logicalPath, `binding ${repositoryId} declares repositoryId ${String(resource.value.repositoryId)}`));
} else {
mapResource(resource, repositories, loadIssues);
definitionValidated = repositories.get(repositoryId) === resource;
}
} catch (error) {
if (error instanceof KxmConfigError) loadIssues.push(...error.issues);
else throw error;
}
} else if (required2 || hasLocalBinding) {
loadIssues.push(issue3("discovery", "repository_definition_missing", `.kxm/repositories/${repositoryId}/repo.yaml`, `${hasLocalBinding ? "explicit" : "required"} repository ${repositoryId} has no repo.yaml`));
}
const environmentFile = join3(binding, ".kxm", "repo", "env.yaml");
if (existsSync4(environmentFile)) {
if (!definitionValidated) {
loadIssues.push(issue3("reference", "repository_environment_without_definition", `.kxm/repositories/${repositoryId}/env.yaml`, `repository ${repositoryId} environment requires a validated matching repo.yaml`));
} else {
try {
environments.push(readResource(registry, root, environmentFile, `.kxm/repositories/${repositoryId}/env.yaml`, "environment", void 0, binding));
} catch (error) {
if (error instanceof KxmConfigError) loadIssues.push(...error.issues);
else throw error;
}
}
}
}
if (loadIssues.length > 0) throw new KxmConfigError([...loadIssues, ...modelIssues]);
const issues = [...modelIssues, ...validateBundle(project, repositories, agents, models, workflows, environments, options, gateRegistry, root, roles)];
if (issues.length > 0) throw new KxmConfigError(issues);
const resources = [project, ...repositories.values(), ...agents.values(), ...models.values(), ...roles.values(), ...workflows.values(), ...environments, ...gateRegistry ? [gateRegistry] : []].sort((left, right) => compareCodeUnits4(left.logicalPath, right.logicalPath));
return {
projectRoot: root,
project,
repositories,
agents,
models,
roles,
workflows,
environments,
...gateRegistry ? { gateRegistry } : {},
...templateProvenance === void 0 ? {} : { templateProvenance },
resources,
configRevision: bundleRevision(resources)
};
}
var LEGACY_CONFIG_FILES = [".kxm/config/agents.json", ".kxm/config/gates.json"];
function legacyConfigFilesAt(root) {
const files = [];
for (const component of [".kxm", ".kxm/config"]) {
const absolute = join3(root, ...component.split("/"));
if (existsSync4(absolute) && lstatSync(absolute).isSymbolicLink()) return [component];
}
for (const candidate of LEGACY_CONFIG_FILES) {
if (existsSync4(join3(root, ...candidate.split("/")))) files.push(candidate);
}
const workflowsDir = join3(root, ".kxm", "config", "workflows");
if (existsSync4(workflowsDir)) {
const stat = lstatSync(workflowsDir);
if (stat.isSymbolicLink()) {
files.push(".kxm/config/workflows");
return files;
}
if (stat.isDirectory()) {
for (const entry of readdirSync2(workflowsDir, { withFileTypes: true }).filter((candidate) => (candidate.isFile() || candidate.isSymbolicLink()) && candidate.name.endsWith(".json")).sort((left, right) => compareCodeUnits4(left.name, right.name))) {
files.push(`.kxm/config/workflows/${entry.name}`);
}
}
}
return files;
}
// plugins/kxm/src/runtime-store.ts
import { spawnSync as spawnSync3 } from "node:child_process";
import { createHash as createHash7, randomUUID } from "node:crypto";
import { existsSync as existsSync7, lstatSync as lstatSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync4, realpathSync as realpathSync3, statSync, writeFileSync as writeFileSync2 } from "node:fs";
import { dirname as dirname5, isAbsolute as isAbsolute4, resolve as resolve6 } from "node:path";
// plugins/kxm/src/sqlite.ts
import { existsSync as existsSync5 } from "node:fs";
import { createRequire } from "node:module";
import { resolve as resolve2 } from "node:path";
import { pathToFileURL as pathToFileURL2 } from "node:url";
var requireFromHere = createRequire(import.meta.url);
function loadNative() {
try {
const mod = requireFromHere("node:sqlite");
if (mod.DatabaseSync) return { Ctor: mod.DatabaseSync, bun: false };
} catch {
}
try {
const mod = requireFromHere("bun:sqlite");
const Ctor = mod?.DatabaseSync ?? mod?.Database;
if (Ctor) return { Ctor, bun: true };
} catch {
}
throw new Error("kxm: no supported sqlite module found (need node:sqlite or bun:sqlite)");
}
var native = loadNative();
var DatabaseSync = class {
inner;
constructor(path, options) {
let normalized = options;
if (native.bun && options) {
const { readOnly, ...rest } = options;
normalized = readOnly === void 0 ? rest : { ...rest, readonly: readOnly };
}
this.inner = normalized === void 0 ? new native.Ctor(path) : new native.Ctor(path, normalized);
}
prepare(sql) {
return this.inner.prepare(sql);
}
exec(sql) {
return this.inner.exec(sql);
}
close() {
this.inner.close();
}
};
function openReadOnlyDatabase(path) {
if (existsSync5(`${path}-wal`)) return new DatabaseSync(path, { readOnly: true });
const uri = pathToFileURL2(resolve2(path));
uri.searchParams.set("immutable", "1");
return new DatabaseSync(uri.href, { readOnly: true });
}
// plugins/kxm/src/runtime-paths.ts
import { createHash as createHash4 } from "node:crypto";
import { realpathSync as realpathSync2 } from "node:fs";
import { join as join5, resolve as resolve4 } from "node:path";
// plugins/kxm/src/bindings.ts
import { homedir } from "node:os";
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4, parse, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
var MAX_BINDING_RECORD_BYTES = 256 * 1024;
var BINDING_LABEL = "Runtime-local repository bindings";
function bindingIssue(phase, code, message) {
return { phase, code, file: BINDING_LABEL, message };
}
function bindingError(phase, code, message) {
throw new KxmConfigError([bindingIssue(phase, code, message)]);
}
function kxmUserStateRoot(options = {}) {
const env = options.env ?? process.env;
const platform = options.platform ?? process.platform;
const home = options.homeDir ?? homedir();
const explicit = options.stateRoot ?? env.KXM_STATE_HOME?.trim();
if (explicit) {
if (!isAbsolute2(explicit)) bindingError("path", "local_state_root_not_absolute", "KXM_STATE_HOME must be an absolute host-local path");
return resolve3(explicit);
}
if (platform === "win32") {
const localAppData = env.LOCALAPPDATA?.trim();
const base2 = localAppData && isAbsolute2(localAppData) ? localAppData : join4(home, "AppData", "Local");
return resolve3(base2, "KXM");
}
if (platform === "darwin") return resolve3(home, "Library", "Application Support", "KXM");
const xdgState = env.XDG_STATE_HOME?.trim();
const base = xdgState && isAbsolute2(xdgState) ? xdgState : join4(home, ".local", "state");
return resolve3(base, "kxm");
}
// plugins/kxm/src/runtime-paths.ts
function kxmRuntimePaths(options = {}) {
const stateRoot = options.stateRoot ? resolve4(options.stateRoot) : kxmUserStateRoot({ ...options.env ? { env: options.env } : {}, ...options.homeDir ? { homeDir: options.homeDir } : {} });
const runtimeDir = join5(stateRoot, "runtime");
return {
stateRoot,
runtimeDir,
registryDb: join5(runtimeDir, "registry.db"),
projectsDir: join5(runtimeDir, "projects")
};
}
function projectRuntimeKey(projectRoot) {
let canonical;
try {
canonical = realpathSync2.native(resolve4(projectRoot));
} catch {
canonical = resolve4(projectRoot);
}
const folded = process.platform === "win32" ? canonical.toLocaleLowerCase("en-US") : canonical;
return createHash4("sha256").update(folded, "utf8").digest("hex").slice(0, 24);
}
function kxmProjectRunEventsPath(projectRoot, env) {
return join5(kxmRuntimePaths({ env }).projectsDir, projectRuntimeKey(projectRoot), "run-events.db");
}
// plugins/kxm/src/sync-transform.ts
import { createHash as createHash5 } from "node:crypto";
// plugins/kxm/src/redact.ts
var SECRET_PATTERNS = [
/\bsk-[A-Za-z0-9_-]{8,}\b/g,
/\bsk-ant-[A-Za-z0-9_-]{8,}\b/g,
/\bghp_[A-Za-z0-9_]{20,}\b/g,
/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/gi,
/\bBearer\s+[A-Za-z0-9._~+/=-]+\b/gi,
/\bya29\.[A-Za-z0-9._~+/-]+=*/g,
/\b1\/\/[A-Za-z0-9_-]+/g,
/\b1\/[A-Za-z0-9_-]{20,}/g,
/("?(?:access_token|refresh_token|id_token|sessionKey|session_key|claude_oauth_token|anthropicApiKey)"?\s*[:=]\s*")[^"]*(")/gi,
/\bKXM_[A-Z0-9_]*(TOKEN|SECRET|KEY)[A-Z0-9_]*=\S+/gi,
/\b(GITHUB_TOKEN|GH_TOKEN|KXM_AUTH_TOKEN|KXM_WORKFLOW_SIGNAL_SECRET|ANTHROPIC_API_KEY|ANTHROPIC_AUTH_TOKEN|CLAUDE_API_KEY)=\S+/gi,
/\b[A-Fa-f0-9]{64}\b/g
];
function redactSecrets(value) {
let result = value;
for (const pattern of SECRET_PATTERNS) {
result = result.replace(pattern, "[redacted]");
}
return result;
}
// plugins/kxm/src/sync-transform.ts
var KXM_SYNC_EVENT_SCHEMA = "kxm.sync-event.v1";
var KXM_SYNC_REDACTOR_VERSION = "redactor-v1";
var KXM_DEFAULT_SYNC_POLICY = Object.freeze({
prompts: "title-only",
results: "bounded-summary",
evidence: "references",
artifacts: "metadata",
fileChanges: "paths-only",
rawLogs: false,
diffs: false,
environmentValues: false
});
var KXM_DEFAULT_SYNC_POLICY_REVISION = `sha256:${createHash5("sha256").update(kxmCanonicalJson(KXM_DEFAULT_SYNC_POLICY), "utf8").digest("hex")}`;
var MIN_REGISTERED_SECRET_CHARS = 4;
var REDACTED = "[redacted]";
var PATH_REDACTED = "[path]";
var CREDENTIAL_SHAPES = [
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
/\bssh-(?:rsa|ed25519|dss|ecdsa-[a-z0-9-]+) AAAA[0-9A-Za-z+/=]+/g,
/\bAKIA[0-9A-Z]{16}\b/g,
/\bgh[opsu]_[A-Za-z0-9]{20,}\b/g,
/\b(?:api[_-]?key|token|secret|password|passwd)\s*[:=]\s*\S+/gi
];
var URL_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi;
var ABSOLUTE_PATHS = [
/\\\\[^\s\\"'`]+\\[^\s"'`]*/g,
// UNC
/\b[A-Za-z]:[\\/][^\s"'`]*/g,
// Windows drive
/(?<![\w.~:/-])~[\\/][^\s"'`]*/g,
// home
/(?<![\w.~:/-])\/(?:[\w.@%+-]+\/)*[\w.@%+-]+\/?/g
// POSIX
];
var CONTROL_CHARACTERS = /[\u0000-\u001F\u007F]/g;
var KxmSyncRedactor = class {
values = /* @__PURE__ */ new Set();
register(value) {
const trimmed = value.trim();
if (trimmed.length >= MIN_REGISTERED_SECRET_CHARS) this.values.add(trimmed);
}
get size() {
return this.values.size;
}
/** Scrub one free-text value; `replaced` counts every substitution. */
scrub(input) {
let replaced = 0;
let text = input;
for (const secret of [...this.values].sort((left, right) => right.length - left.length)) {
const parts = text.split(secret);
if (parts.length > 1) {
replaced += parts.length - 1;
text = parts.join(REDACTED);
}
}
const substitute = (pattern, replacement) => {
text = text.replace(pattern, (...args) => {
replaced += 1;
return typeof replacement === "string" ? replacement : replacement(...args);
});
};
for (const pattern of CREDENTIAL_SHAPES) substitute(pattern, REDACTED);
substitute(URL_USERINFO, (_match, scheme) => `${scheme}${REDACTED}@`);
const shaped = redactSecrets(text);
if (shaped !== text) {
replaced += shaped.split(REDACTED).length - text.split(REDACTED).length;
text = shaped;
}
for (const pattern of ABSOLUTE_PATHS) substitute(pattern, PATH_REDACTED);
text = text.replace(CONTROL_CHARACTERS, " ").replace(/\s+/g, " ").trim();
return { text, replaced };
}
};
function isRecord(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function pickScalars(source, keys, redactor) {
if (!isRecord(source)) return void 0;
const result = {};
for (const key of keys) {
const value = source[key];
if (typeof value === "number" || typeof value === "boolean") {
result[key] = value;
} else if (typeof value === "string") {
if (redactor) {
const scrubbed = redactor.scrub(value);
if (scrubbed.text.length > 0) result[key] = scrubbed.text.slice(0, 200);
} else {
result[key] = value;
}
}
}
return Object.keys(result).length > 0 ? result : void 0;
}
var SyncPayloadBuilder = class {
payload = {};
omitted = /* @__PURE__ */ new Set();
replaced = 0;
redactor;
constructor(redactor) {
this.redactor = redactor;
}
/** Bounded, scrubbed free text; empty after scrubbing means absent. */
text(value, max) {
if (typeof value !== "string") return void 0;
const { text, replaced } = this.redactor.scrub(value);
this.replaced += replaced;
if (text.length === 0) return void 0;
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
}
/** A nested record rebuilt key by key, with the named keys scrubbed as text. */
record(source, keys, textKeys = {}) {
const scalars = pickScalars(source, keys.filter((key) => !(key in textKeys)));
const result = { ...scalars ?? {} };
if (isRecord(source)) {
for (const [key, max] of Object.entries(textKeys)) {
const value = this.text(source[key], max);
if (value !== void 0) result[key] = value;
}
}
return Object.keys(result).length > 0 ? result : void 0;
}
set(key, value) {
if (value !== void 0) this.payload[key] = value;
}
};
var SCALAR_FIELDS = [
"workflowId",
"promptHash",
"status",
"previousStatus",
"outcome",
"stepId",
"stepAttempt",
"fromStepId",
"toStepId",
"assignmentId",
"attemptId",
"agentId",
"instanceNo",
"scopeEpoch",
"resolutionAction"
];
var REF_KEYS = ["id", "kind", "hash", "status", "producerId"];
var ARTIFACT_KEYS = ["id", "kind", "hash", "size", "classification", "availability"];
var LEASE_KEYS = ["id", "fencingToken", "acquiredAt", "expiresAt", "operation"];
var MAX_REFS = 64;
var CARRIED_FIELDS = /* @__PURE__ */ new Set([
...SCALAR_FIELDS,
"displayTitle",
"summary",
"reason",
"executor",
"model",
"timing",
"usage",
"evidenceRefs",
"artifacts",
"receipt",
"error",
"effect",
"lease",
"actor",
"resolvedBy",
"suppliedRefs",
"counts"
]);
var CONTROL_FIELDS = ["effect", "lease", "actor", "resolvedBy", "resolutionAction", "reason", "suppliedRefs", "outcome"];
function buildPayload(source, builder) {
for (const key of SCALAR_FIELDS) {
const value = source[key];
if (typeof value === "string" || typeof value === "number") builder.set(key, value);
}
builder.set("displayTitle", builder.text(source.displayTitle, 200));
builder.set("summary", builder.text(source.summary, 1e3));
if (source.reason !== void 0) {
builder.set("reason", builder.text(source.reason, 1e3) ?? REDACTED);
}
builder.set("executor", builder.record(source.executor, ["id", "kind", "harness"], {
executorVersion: 128,
harnessVersion: 128,
helperGeneration: 256
}));
const model = builder.record(source.model, ["profile", "provider"], { model: 200, thinking: 64 });
if (model && isRecord(source.model) && Array.isArray(source.model.tags)) {
model.tags = source.model.tags.filter((tag) => typeof tag === "string").slice(0, 32);
}
builder.set("model", model);
builder.set("timing", builder.record(source.timing, ["startedAt", "finishedAt", "durationMs", "queueMs", "agentMs"]));
builder.set("usage", builder.record(source.usage, [
"inputTokens",
"outputTokens",
"cacheReadTokens",
"cacheWriteTokens",
"cost",
"currency",
"costKind"
]));
const refs = (value, keys) => Array.isArray(value) ? value.slice(0, MAX_REFS).map((entry) => pickScalars(entry, keys)).filter((entry) => entry !== void 0) : void 0;
builder.set("evidenceRefs", refs(source.evidenceRefs, REF_KEYS));
builder.set("suppliedRefs", refs(source.suppliedRefs, REF_KEYS));
builder.set("artifacts", refs(source.artifacts, ARTIFACT_KEYS));
if (isRecord(source.receipt)) {
const receipt = builder.record(source.receipt, ["provider", "kind", "hash", "observedAt"], { id: 512 });
if (receipt) builder.set("receipts", [receipt]);
if (source.receipt.url !== void 0) builder.omitted.add("receipt.url");
}
builder.set("error", builder.record(source.error, ["class", "retryable"], { component: 128 }));
if (isRecord(source.effect)) {
const effect = pickScalars(source.effect, ["id", "idempotencyKeyHash"], builder.redactor) ?? {};
const policy = pickScalars(source.effect.policy, ["class", "sharedMutable", "idempotencyKey", "receiptQuery"], builder.redactor);
if (policy) effect.policy = policy;
builder.set("effect", effect);
}
builder.set("lease", pickScalars(source.lease, LEASE_KEYS, builder.redactor));
builder.set("actor", builder.record(source.actor, ["kind"], { id: 200 }));
builder.set("resolvedBy", builder.record(source.resolvedBy, ["kind"], { id: 200 }));
if (isRecord(source.counts)) {
const counts = Object.fromEntries(Object.entries(source.counts).filter((entry) => Number.isInteger(entry[1]) && entry[1] >= 0).slice(0, 32));
builder.set("counts", counts);
}
}
function envelope(event, policyRevision, payload, fieldsOmitted, valuesReplaced) {
return {
schema: KXM_SYNC_EVENT_SCHEMA,
sourceEventId: event.eventId,
eventType: event.eventType,
projectId: event.projectId,
runId: event.runId,
homeRuntimeId: event.homeRuntimeId,
sequence: event.sequence,
occurredAt: event.occurredAt,
configRevision: event.configRevision,
memoryRevision: event.memoryRevision,
executorPolicyRevision: event.executorPolicyRevision,
toolPolicyRevision: event.toolPolicyRevision,
syncPolicyRevision: policyRevision,
redaction: {
version: KXM_SYNC_REDACTOR_VERSION,
fieldsOmitted: [...new Set(fieldsOmitted)].sort().slice(0, 128),
valuesReplaced: Math.min(valuesReplaced, 1e5)
},
payload
};
}
function deriveKxmSyncEvent(event, options = {}) {
const redactor = options.redactor ?? new KxmSyncRedactor();
const policyRevision = options.policyRevision ?? KXM_DEFAULT_SYNC_POLICY_REVISION;
const source = isRecord(event.payload) ? event.payload : {};
const builder = new SyncPayloadBuilder(redactor);
buildPayload(source, builder);
const omitted = new Set(builder.omitted);
for (const key of Object.keys(source)) if (!CARRIED_FIELDS.has(key)) omitted.add(key);
if (event.protectedPayload !== void 0) omitted.add("protectedPayload");
const payload = Object.keys(builder.payload).length > 0 ? builder.payload : { counts: {} };
const full = envelope(event, policyRevision, payload, omitted, builder.replaced);
if (syncEventSchemaErrors(full) === void 0) return full;
const degradedPayload = { degraded: true };
for (const key of CONTROL_FIELDS) {
const value = builder.payload[key];
const restoreNested = (built, orig) => {
if (!isRecord(orig)) return built !== void 0 ? built : "[redacted]";
const result = {};
const builtRecord = isRecord(built) ? built : {};
for (const [k, v] of Object.entries(orig)) {
const builtValue = builtRecord[k];
if (builtValue === void 0 || typeof builtValue === "string" && builtValue.trim().length === 0) {
result[k] = isRecord(v) ? restoreNested(void 0, v) : "[redacted]";
} else {
result[k] = builtValue;
}
}
return result;
};
if (value === void 0) {
const sourceValue = source[key];
if (sourceValue !== void 0) {
degradedPayload[key] = restoreNested(void 0, sourceValue);
}
} else if (typeof value === "string" && value.trim().length === 0) {
degradedPayload[key] = "[redacted]";
} else if (isRecord(value)) {
degradedPayload[key] = restoreNested(value, source[key]);
} else {
degradedPayload[key] = value;
}
}
const degradedOmitted = new Set(omitted);
for (const key of Object.keys(builder.payload)) if (!(key in degradedPayload)) degradedOmitted.add(key);
const degraded = envelope(event, policyRevision, degradedPayload, degradedOmitted, builder.replaced);
const errors = syncEventSchemaErrors(degraded);
if (errors === void 0) return degraded;
throw new KxmConfigError([{
phase: "schema",
code: "sync_event_invalid",
file: `${event.runId}#${event.sequence}`,
message: `event cannot be derived into kxm.sync-event.v1: ${errors}`
}]);
}
function kxmSyncEventBytes(event) {
return kxmCanonicalJson(event);
}
// plugins/kxm/src/database.ts
import { createHash as createHash6, randomBytes } from "node:crypto";
import {
chmodSync,
copyFileSync,
existsSync as existsSync6,
lstatSync as lstatSync2,
mkdirSync,
readdirSync as readdirSync3,
readFileSync as readFileSync3,
unlinkSync,
writeFileSync
} from "node:fs";
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
function databaseError(code, file, message) {
const issue4 = { phase: "semantic", code, file, message };
return new KxmConfigError([issue4]);
}
function checkedParent(path, description) {
const parent = dirname4(path);
if (!existsSync6(parent)) mkdirSync(parent, { recursive: true, mode: 448 });
const stat = lstatSync2(parent, { throwIfNoEntry: false });
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) {
throw databaseError("runtime_path_invalid", description, `${description} parent must be a regular directory, not a link`);
}
}
function userTables(database) {
const rows = database.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
).all();
return rows.map((row) => row.name);
}
function tableColumns(database, table) {
const rows = database.prepare(`PRAGMA table_info(${table})`).all();
return rows.map((row) => row.name).sort();
}
function verifyExpectedTables(database, file, description, expected) {
const present = new Set(userTables(database));
for (const [table, columns] of Object.entries(expected)) {
if (!present.has(table)) {
throw databaseError("runtime_schema_shape_invalid", file, `${description} is missing table ${table}`);
}
const actual = tableColumns(database, table);
const missing = columns.filter((column) => !actual.includes(column));
if (missing.length > 0) {
throw databaseError("runtime_schema_shape_invalid", file, `${description} table ${table} is missing columns ${missing.join(", ")}`);
}
}
}
function ensureWalJournalMode(database, file, description, timeoutMs = 5e3) {
const deadline = Date.now() + timeoutMs;
const sleeper = new Int32Array(new SharedArrayBuffer(4));
while (true) {
try {
const current = database.prepare("PRAGMA journal_mode").get();
if (current?.journal_mode === "wal") {
return;
}
const updated = database.prepare("PRAGMA journal_mode = WAL").get();
if (updated?.journal_mode === "wal") {
return;
}
} catch (error) {
const sqliteError = error;
if (sqliteError.code === "ERR_SQLITE_ERROR" && sqliteError.errcode === 5 && Date.now() < deadline) {
Atomics.wait(sleeper, 0, 0, 10);
continue;
}
throw error;
}
if (Date.now() >= deadline) {
throw databaseError("runtime_timeout", file, `${description} timed out enabling WAL journal mode`);
}
Atomics.wait(sleeper, 0, 0, 10);
}
}
function assertDatabaseFile(file, description) {
checkedParent(file, description);
const stat = lstatSync2(file, { throwIfNoEntry: false });
if (stat) {
if (stat.isSymbolicLink() || !stat.isFile()) {
throw databaseError("runtime_path_invalid", description, `${description} must be a regular file, not a link or directory`);
}
}
for (const sidecar of [`${file}-wal`, `${file}-shm`]) {
const info = lstatSync2(sidecar, { throwIfNoEntry: false });
if (info?.isSymbolicLink()) {
throw databaseError("runtime_path_invalid", description, `${description} sidecar must not be a link`);
}
}
}
function openDatabase(file, description, spec) {
const isMemory = file === ":memory:";
if (!isMemory) {
assertDatabaseFile(file, description);
}
const database = new DatabaseSync(file);
let transaction = false;
try {
database.exec(`PRAGMA busy_timeout = ${spec.timeoutMs ?? 5e3}`);
if (!isMemory) {
ensureWalJournalMode(database, file, description, spec.timeoutMs);
}
database.exec("PRAGMA synchronous = NORMAL");
database.exec("PRAGMA foreign_keys = ON");
database.exec("BEGIN IMMEDIATE");
transaction = true;
const row = database.prepare("PRAGMA user_version").get();
const version = row?.user_version ?? 0;
if (version > spec.version) {
throw databaseError("runtime_schema_newer", file, `${description} schema version ${version} is newer than this runtime supports`);
}
if (version === 0) {
const existing = userTables(database);
if (existing.length > 0) {
throw databaseError("runtime_schema_shape_invalid", file, `${description} has tables at schema version 0`);
}
database.exec(spec.schema);
database.exec(`PRAGMA user_version = ${spec.version}`);
} else if (version < spec.version) {
throw databaseError(
"runtime_schema_outdated",
file,
`${description} is schema version ${version}; this build requires ${spec.version}. Delete the state file to start fresh and let its owning process recreate it (\`kxm hub start\` for hub state, the Runtime for event stores). The Runtime registry copy from schema 1 to 2 is the one exception. \`kxm init\` is project-only and rebuilds no database. Upgrading any other old state in place is deliberately unsupported`
);
}
if (spec.tables) {
verifyExpectedTables(database, file, description, spec.tables);
}
database.exec("COMMIT");
transaction = false;
return database;
} catch (error) {
if (transaction) {
try {
database.exec("ROLLBACK");
} catch {
}
}
database.close();
throw error;
}
}
var activeTransactions = /* @__PURE__ */ new WeakSet();
var TRANSACTION_BUSY_BACKOFF_MS = 1e3;
function monotonicNowMs() {
return Number(process.hrtime.bigint() / 1000000n);
}
var transactionThrottles = /* @__PURE__ */ new WeakMap();
function finiteNow(clock, label) {
const now = clock();
if (typeof now !== "number" || !Number.isFinite(now)) {
throw databaseError(
"runtime_transaction_clock_invalid",
"transaction",
`${label} must return a finite monotonic number; got ${String(now)}`
);
}
return now;
}
var CONTENTION_PRIMARY_CODES = [5, 6, 15];
var CONTENTION_SYMBOLIC_NAMES = /^SQLITE_(?:BUSY|LOCKED|PROTOCOL)(?:_[A-Z0-9]+)?$/;
var SQLITE_RESULT_NAMES = /^SQLITE_[A-Z][A-Z0-9_]*$/;
var CONTENTION_MESSAGES = /^(?:database is locked|database table is locked|locking protocol|SQLITE_BUSY|SQLITE_LOCKED|SQLITE_PROTOCOL)(?:$|[\s.:])/i;
function isTransactionContention(error) {
const carrier = error;
for (const value of [carrier?.errcode, carrier?.errCode, carrier?.errno]) {
if (typeof value === "number" && Number.isInteger(value)) return CONTENTION_PRIMARY_CODES.includes(value & 255);
}
for (const value of [carrier?.code, carrier?.name]) {
if (typeof value === "string" && SQLITE_RESULT_NAMES.test(value)) {
return CONTENTION_SYMBOLIC_NAMES.test(value);
}
}
return CONTENTION_MESSAGES.test(error instanceof Error ? error.message : String(error));
}
function withDatabaseTransaction(database, work, mode = "IMMEDIATE", clock = monotonicNowMs) {
if (activeTransactions.has(database)) {
throw databaseError("runtime_transaction_nested", "transaction", "nested transactions are not allowed");
}
if (mode !== "DEFERRED") {
const deadlines = transactionThrottles.get(database);
const until = deadlines?.get(clock);
if (until !== void 0) {
const remaining = until - finiteNow(clock, "the transaction clock");
if (remaining > 0) {
throw databaseError(
"runtime_transaction_busy",
"transaction",
`a previous BEGIN was blocked on this database; retry deferred ${String(remaining)}ms`
);
}
deadlines?.delete(clock);
}
}
try {
database.exec(`BEGIN ${mode}`);
} catch (error) {
if (!isTransactionContention(error)) throw error;
const now = finiteNow(clock, "the transaction clock");
let deadlines = transactionThrottles.get(database);
if (deadlines === void 0) {
deadlines = /* @__PURE__ */ new WeakMap();
transactionThrottles.set(database, deadlines);
}
deadlines.set(clock, now + TRANSACTION_BUSY_BACKOFF_MS);
throw databaseError(
"runtime_transaction_busy",
"transaction",
`BEGIN ${mode} blocked by another transaction: ${error instanceof Error ? error.message : String(error)}`
);
}
activeTransactions.add(database);
if (mode !== "DEFERRED") transactionThrottles.get(database)?.delete(clock);
try {
const result = work();
database.exec("COMMIT");
return result;
} catch (error) {
try {
database.exec("ROLLBACK");
} catch {
}
throw error;
} finally {
activeTransactions.delete(database);
}
}
function checkpointWal(database, mode = "TRUNCATE") {
const row = database.prepare(`PRAGMA wal_checkpoint(${mode})`).get();
return {
busy: row?.busy ?? 0,
log: row?.log ?? 0,
checkpointed: row?.checkpointed ?? 0
};
}
function checkIntegrity(database) {
const rows = database.prepare("PRAGMA integrity_check").all();
return rows.length === 1 && rows[0]?.integrity_check === "ok";
}
function fileSha256(filePath) {
const bytes = readFileSync3(filePath);
return `sha256:${createHash6("sha256").update(bytes).digest("hex")}`;
}
function backupDatabaseFile(sourcePath2, targetPath, storeId) {
const resolvedSource = resolve5(sourcePath2);
const resolvedTarget = resolve5(targetPath);
const sourceStat = lstatSync2(resolvedSource, { throwIfNoEntry: false });
if (!sourceStat || !sourceStat.isFile() || sourceStat.isSymbolicLink()) {
throw databaseError("runtime_path_invalid", resolvedSource, `source database ${resolvedSource} must be a regular file, not a link or directory`);
}
checkedParent(resolvedTarget, "backup target");
if (existsSync6(resolvedTarget)) {
unlinkSync(resolvedTarget);
}
const sourceDb = new DatabaseSync(resolvedSource);
let schemaVersion = 0;
try {
sourceDb.exec("PRAGMA busy_timeout = 5000");
checkpointWal(sourceDb, "TRUNCATE");
if (!checkIntegrity(sourceDb)) {
throw databaseError("database_corrupted", resolvedSource, `database ${resolvedSource} failed integrity check`);
}
const versionRow = sourceDb.prepare("PRAGMA user_version").get();
schemaVersion = versionRow?.user_version ?? 0;
const escapedTarget = resolvedTarget.replace(/\x27/g, "''");
sourceDb.exec(`VACUUM INTO '${escapedTarget}'`);
} finally {
sourceDb.close();
}
const targetDb = new DatabaseSync(resolvedTarget);
try {
targetDb.exec("PRAGMA busy_timeout = 5000");
if (!checkIntegrity(targetDb)) {
throw databaseError("database_corrupted", resolvedTarget, `backup database ${resolvedTarget} failed integrity check`);
}
} finally {
targetDb.close();
}
try {
chmodSync(resolvedTarget, 384);
} catch {
}
const sha256 = fileSha256(resolvedTarget);
const bytes = lstatSync2(resolvedTarget).size;
return {
storeId,
sourcePath: resolvedSource,
backupFile: basename2(resolvedTarget),
schemaVersion,
sha256,
bytes,
integrity: "ok"
};
}
function restoreDatabaseFile(backupPath, targetPath, storeId, expectedSchemaVersion, maxSupportedVersion) {
const resolvedBackup = resolve5(backupPath);
const resolvedTarget = resolve5(targetPath);
const backupStat = lstatSync2(resolvedBackup, { throwIfNoEntry: false });
if (!backupStat || !backupStat.isFile() || backupStat.isSymbolicLink()) {
throw databaseError("runtime_path_invalid", resolvedBackup, `backup database ${resolvedBackup} must be a regular file, not a link or directory`);
}
const backupDb = new DatabaseSync(resolvedBackup);
let schemaVersion = 0;
try {
backupDb.exec("PRAGMA busy_timeout = 5000");
if (!checkIntegrity(backupDb)) {
throw databaseError("database_corrupted", resolvedBackup, `backup database ${resolvedBackup} failed integrity check`);
}
const versionRow = backupDb.prepare("PRAGMA user_version").get();
schemaVersion = versionRow?.user_version ?? 0;
if (maxSupportedVersion !== void 0 && schemaVersion > maxSupportedVersion) {
throw databaseError(
"runtime_schema_newer",
resolvedBackup,
`backup store ${storeId} schema version ${schemaVersion} is newer than supported maximum ${maxSupportedVersion}`
);
}
if (expectedSchemaVersion !== void 0 && schemaVersion !== expectedSchemaVersion) {
throw databaseError(
"runtime_schema_mismatch",
resolvedBackup,
`backup store ${storeId} schema version ${schemaVersion} does not match manifest version ${expectedSchemaVersion}`
);
}
} finally {
backupDb.close();
}
checkedParent(resolvedTarget, "restore target");
for (const file of [resolvedTarget, `${resolvedTarget}-wal`, `${resolvedTarget}-shm`]) {
if (existsSync6(file)) {
try {
unlinkSync(file);
} catch {
}
}
}
copyFileSync(resolvedBackup, resolvedTarget);
try {
chmodSync(resolvedTarget, 384);
} catch {
}
const targetDb = new DatabaseSync(resolvedTarget);
try {
targetDb.exec("PRAGMA busy_timeout = 5000");
if (!checkIntegrity(targetDb)) {
throw databaseError("database_corrupted", resolvedTarget, `restored database ${resolvedTarget} failed integrity check`);
}
} finally {
targetDb.close();
}
return {
storeId,
sourcePath: resolvedTarget,
backupFile: basename2(resolvedBackup),
schemaVersion,
integrity: "ok"
};
}
var KXM_BACKUP_CEILINGS = {
"hub-store": 5,
registry: 2,
"binding-store": 1,
events: 7
};
function kxmBackupCeiling(storeId) {
if (storeId === "runtime-registry") return KXM_BACKUP_CEILINGS.registry;
if (storeId.startsWith("events:")) return KXM_BACKUP_CEILINGS.events;
return KXM_BACKUP_CEILINGS[storeId] ?? KXM_BACKUP_CEILINGS["hub-store"];
}
function pushStore(stores, storeId, sourcePath2) {
if (stores.some((store) => store.storeId === storeId || store.sourcePath === sourcePath2)) return;
stores.push({ storeId, sourcePath: sourcePath2, maxSupportedVersion: kxmBackupCeiling(storeId) });
}
function pushEventStore(stores, files, paths, key) {
const dbPath = join6(paths.projectsDir, key, "run-events.db");
if (!existsSync6(dbPath)) return;
const safe = key.replace(/[^a-zA-Z0-9_.-]/g, "_");
let storeId = `events:${safe}`;
if (stores.some((store) => store.storeId === storeId)) storeId = `events:runtime:${safe}`;
pushStore(stores, storeId, dbPath);
const sidecar = `${dbPath}.run-prompts.json`;
if (existsSync6(sidecar)) {
const id = `${storeId}:run-prompts`;
if (!files.some((file) => file.id === id || file.sourcePath === sidecar)) {
files.push({ id, sourcePath: sidecar });
}
}
}
function discoverUserRuntime(runtimeProjectKey, options, stores, files) {
let paths;
try {
paths = kxmRuntimePaths(options.env ? { env: options.env } : {});
} catch {
return void 0;
}
if (!options.allProjects) {
pushEventStore(stores, files, paths, runtimeProjectKey);
return paths.stateRoot;
}
if (existsSync6(paths.registryDb)) {
const storeId = stores.some((store) => store.storeId === "registry") ? "runtime-registry" : "registry";
pushStore(stores, storeId, paths.registryDb);
}
if (!existsSync6(paths.projectsDir)) return paths.stateRoot;
let entries;
try {
entries = readdirSync3(paths.projectsDir, { withFileTypes: true });
} catch {
return paths.stateRoot;
}
for (const entry of entries) {
if (entry.isDirectory()) pushEventStore(stores, files, paths, entry.name);
}
return paths.stateRoot;
}
function discoverBackupSources(projectRoot, options = {}) {
const root = resolve5(projectRoot);
const stores = [];
const files = [];
const hubPath = options.hubDataPath ? resolve5(options.hubDataPath) : join6(root, ".kxm", "state", "kxm.db");
if (existsSync6(hubPath)) pushStore(stores, "hub-store", hubPath);
const registryPath = join6(root, ".kxm", "runtime", "registry.db");
if (existsSync6(registryPath)) pushStore(stores, "registry", registryPath);
const bindingsPath = join6(root, ".kxm", "runtime", "bindings.db");
if (existsSync6(bindingsPath)) pushStore(stores, "binding-store", bindingsPath);
const eventsDir = join6(root, ".kxm", "runtime", "events");
if (existsSync6(eventsDir)) {
const entries = readdirSync3(eventsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith(".db")) {
const key = entry.name.replace(/\.db$/, "").replace(/[^a-zA-Z0-9_.-]/g, "_");
pushStore(stores, `events:${key}`, join6(eventsDir, entry.name));
}
}
}
const runtimeProjectKey = projectRuntimeKey(root);
const stateRoot = discoverUserRuntime(runtimeProjectKey, options, stores, files);
return { stores, files, runtimeProjectKey, ...stateRoot !== void 0 ? { stateRoot } : {} };
}
function backupPlainFile(sourcePath2, targetPath, id) {
const resolvedSource = resolve5(sourcePath2);
const sourceStat = lstatSync2(resolvedSource, { throwIfNoEntry: false });
if (!sourceStat || !sourceStat.isFile() || sourceStat.isSymbolicLink()) {
throw databaseError("runtime_path_invalid", resolvedSource, `backup file ${resolvedSource} must be a regular file, not a link or directory`);
}
checkedParent(targetPath, "backup target");
if (existsSync6(targetPath)) unlinkSync(targetPath);
copyFileSync(resolvedSource, targetPath);
try {
chmodSync(targetPath, 384);
} catch {
}
return {
id,
sourcePath: resolvedSource,
backupFile: basename2(targetPath),
sha256: fileSha256(targetPath),
bytes: sourceStat.size
};
}
function backupFilename(sourcePath2, id, used) {
let filename = basename2(sourcePath2);
if (used.has(filename)) {
filename = `${id.replace(/[^a-zA-Z0-9_.-]/g, "_")}-${filename}`;
}
used.add(filename);
return filename;
}
function restorePlainFile(backupFilePath, targetPath) {
checkedParent(targetPath, "restore target");
if (existsSync6(targetPath)) unlinkSync(targetPath);
copyFileSync(backupFilePath, targetPath);
try {
chmodSync(targetPath, 384);
} catch {
}
}
function discoverProjectStores(projectRoot, options = {}) {
return discoverBackupSources(projectRoot, options).stores;
}
function backupDiscoverOptions(options) {
return {
...options.hubDataPath !== void 0 ? { hubDataPath: options.hubDataPath } : {},
...options.env !== void 0 ? { env: options.env } : {},
...options.allProjects === true ? { allProjects: true } : {}
};
}
function planBackup(options = {}) {
const projectRoot = options.projectRoot ? resolve5(options.projectRoot) : process.cwd();
const discovered = discoverBackupSources(projectRoot, backupDiscoverOptions(options));
if (discovered.stores.length === 0) {
throw databaseError("backup_no_stores", projectRoot, "no existing SQLite stores found to backup");
}
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
const timestamp = createdAt.replace(/[:.]/g, "-");
const outDir = options.outDir ? resolve5(options.outDir) : join6(projectRoot, ".kxm", "backups", `backup-${timestamp}`);
const usedFilenames = /* @__PURE__ */ new Set();
const stores = discovered.stores.map((store) => ({
storeId: store.storeId,
sourcePath: store.sourcePath,
backupFile: backupFilename(store.sourcePath, store.storeId, usedFilenames)
}));
const files = discovered.files.map((file) => ({
id: file.id,
sourcePath: file.sourcePath,
backupFile: backupFilename(file.sourcePath, file.id, usedFilenames)
}));
return {
projectRoot,
outDir,
createdAt,
scope: options.allProjects === true ? "all-projects" : "project",
...discovered.stateRoot !== void 0 ? { stateRoot: discovered.stateRoot } : {},
runtimeProjectKey: discovered.runtimeProjectKey,
stores,
files
};
}
function createBackup(options = {}) {
const { projectRoot, outDir, createdAt, scope, stateRoot, runtimeProjectKey, stores, files } = planBackup(options);
const backupId = `bk_${randomBytes(8).toString("hex")}`;
if (!existsSync6(outDir)) {
mkdirSync(outDir, { recursive: true, mode: 448 });
}
const backedUpStores = [];
const backedUpFiles = [];
const omitted = [];
for (const store of stores) {
try {
backedUpStores.push(backupDatabaseFile(store.sourcePath, join6(outDir, store.backupFile), store.storeId));
} catch {
omitted.push(store.storeId);
}
}
for (const file of files) {
try {
backedUpFiles.push(backupPlainFile(file.sourcePath, join6(outDir, file.backupFile), file.id));
} catch {
omitted.push(file.id);
}
}
if (backedUpStores.length === 0) {
throw databaseError("backup_no_stores", projectRoot, "no SQLite store could be copied");
}
const again = discoverBackupSources(projectRoot, backupDiscoverOptions(options));
for (const store of again.stores) {
if (!backedUpStores.some((copied) => copied.storeId === store.storeId) && !omitted.includes(store.storeId)) {
omitted.push(store.storeId);
}
}
for (const file of again.files) {
if (!backedUpFiles.some((copied) => copied.id === file.id) && !omitted.includes(file.id)) {
omitted.push(file.id);
}
}
const manifest = {
schema: "kxm.backup-manifest.v1",
backupId,
createdAt,
projectRoot,
scope,
...stateRoot !== void 0 ? { stateRoot } : {},
runtimeProjectKey,
stores: backedUpStores,
...backedUpFiles.length > 0 ? { files: backedUpFiles } : {},
complete: omitted.length === 0,
...omitted.length > 0 ? { omitted } : {}
};
const manifestJson = JSON.stringify(manifest, null, 2) + "\n";
const manifestSha256 = `sha256:${createHash6("sha256").update(manifestJson, "utf8").digest("hex")}`;
manifest.manifestSha256 = manifestSha256;
const finalJson = JSON.stringify(manifest, null, 2) + "\n";
const manifestPath = join6(outDir, "manifest.json");
writeFileSync(manifestPath, finalJson, "utf8");
return { manifest, outDir };
}
function pathUnder(root, path) {
if (!root) return void 0;
const rel = relative3(root, path);
if (rel === "" || rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute3(rel)) return void 0;
return rel;
}
function restoreTarget(manifest, sourcePath2, id, options, currentStateRoot) {
const stateRel = pathUnder(manifest.stateRoot, sourcePath2);
const projectRel = pathUnder(manifest.projectRoot, sourcePath2);
if (stateRel !== void 0 && (projectRel === void 0 || stateRel.length <= projectRel.length)) {
const ownEvents = manifest.runtimeProjectKey !== void 0 ? join6("runtime", "projects", manifest.runtimeProjectKey, "run-events.db") : void 0;
const own2 = ownEvents !== void 0 && (stateRel === ownEvents || stateRel === `${ownEvents}.run-prompts.json`);
if (own2 && !options.allProjects && options.projectRoot !== void 0) {
const eventsPath = kxmProjectRunEventsPath(resolve5(options.projectRoot), options.env ?? process.env);
return { targetPath: stateRel === ownEvents ? eventsPath : `${eventsPath}.run-prompts.json`, machineWide: false };
}
return { targetPath: join6(currentStateRoot(), stateRel), machineWide: !own2 };
}
if (projectRel !== void 0) {
return { targetPath: options.projectRoot ? join6(resolve5(options.projectRoot), projectRel) : sourcePath2, machineWide: false };
}
return { targetPath: sourcePath2, machineWide: id !== "hub-store" };
}
function planRestore(manifestPathOrDir, options = {}) {
let manifestPath = resolve5(manifestPathOrDir);
const stat = lstatSync2(manifestPath, { throwIfNoEntry: false });
if (!stat) {
throw databaseError("runtime_path_invalid", manifestPath, `manifest path ${manifestPath} does not exist`);
}
if (stat.isDirectory()) {
manifestPath = join6(manifestPath, "manifest.json");
}
if (!existsSync6(manifestPath)) {
throw databaseError("runtime_path_invalid", manifestPath, `backup manifest ${manifestPath} not found`);
}
const manifestDir = dirname4(manifestPath);
const rawText = readFileSync3(manifestPath, "utf8");
let manifest;
try {
manifest = JSON.parse(rawText);
} catch (error) {
throw databaseError("restore_manifest_invalid", manifestPath, `failed to parse backup manifest: ${error instanceof Error ? error.message : String(error)}`);
}
if (manifest.schema !== "kxm.backup-manifest.v1" || !Array.isArray(manifest.stores) || manifest.stores.length === 0) {
throw databaseError("restore_manifest_invalid", manifestPath, "manifest is not a valid kxm.backup-manifest.v1 document");
}
if (manifest.complete === false) {
throw databaseError("restore_incomplete", manifestPath, "backup manifest is incomplete; refusing to restore a partial copy");
}
let stateRoot;
const currentStateRoot = () => stateRoot ??= kxmRuntimePaths({ env: options.env ?? process.env }).stateRoot;
const machineWide = [];
const stores = [];
for (const store of manifest.stores) {
const backupFilePath = join6(manifestDir, store.backupFile);
if (!existsSync6(backupFilePath)) {
throw databaseError("restore_file_missing", backupFilePath, `backup file ${store.backupFile} missing from ${manifestDir}`);
}
const actualSha256 = fileSha256(backupFilePath);
if (actualSha256 !== store.sha256) {
throw databaseError(
"restore_manifest_digest_mismatch",
backupFilePath,
`backup file ${store.backupFile} sha256 ${actualSha256} does not match manifest hash ${store.sha256}`
);
}
const maxSupportedVersion = kxmBackupCeiling(store.storeId);
if (store.schemaVersion > maxSupportedVersion) {
throw databaseError(
"runtime_schema_newer",
backupFilePath,
`backup store ${store.storeId} schema version ${store.schemaVersion} is newer than supported maximum ${maxSupportedVersion}`
);
}
const target = restoreTarget(manifest, store.sourcePath, store.storeId, options, currentStateRoot);
if (target.machineWide) machineWide.push(store.storeId);
stores.push({ storeId: store.storeId, backupFilePath, targetPath: target.targetPath, schemaVersion: store.schemaVersion, maxSupportedVersion });
}
const files = [];
for (const file of manifest.files ?? []) {
const backupFilePath = join6(manifestDir, file.backupFile);
if (!existsSync6(backupFilePath)) {
throw databaseError("restore_file_missing", backupFilePath, `backup file ${file.backupFile} missing from ${manifestDir}`);
}
const actualSha256 = fileSha256(backupFilePath);
if (actualSha256 !== file.sha256) {
throw databaseError(
"restore_manifest_digest_mismatch",
backupFilePath,
`backup file ${file.backupFile} sha256 ${actualSha256} does not match manifest hash ${file.sha256}`
);
}
const target = restoreTarget(manifest, file.sourcePath, file.id, options, currentStateRoot);
if (target.machineWide) machineWide.push(file.id);
files.push({ id: file.id, backupFilePath, targetPath: target.targetPath });
}
if (machineWide.length > 0 && !options.allProjects) {
throw databaseError(
"restore_requires_all_projects",
manifestPath,
`backup ${manifest.backupId} holds Runtime state shared by every project on this machine (${machineWide.join(", ")}); restoring it rolls back the registry or other projects' runs. Pass --all-projects to restore all of it, or restore a backup taken without --all-projects`
);
}
return {
manifestPath,
backupId: manifest.backupId,
...manifest.scope !== void 0 ? { scope: manifest.scope } : {},
stores,
files
};
}
function applyRestorePlan(plan) {
const restoredStores = plan.stores.map((store) => restoreDatabaseFile(
store.backupFilePath,
store.targetPath,
store.storeId,
store.schemaVersion,
store.maxSupportedVersion
));
for (const file of plan.files) {
restorePlainFile(file.backupFilePath, file.targetPath);
}
return {
manifestPath: plan.manifestPath,
backupId: plan.backupId,
restoredStores
};
}
function restoreBackup(manifestPathOrDir, options = {}) {
return applyRestorePlan(planRestore(manifestPathOrDir, options));
}
// plugins/kxm/src/runtime-store.ts
function runtimeIssue(phase, code, file, message) {
return { phase, code, file, message };
}
function runtimeError(code, file, message) {
return new KxmConfigError([runtimeIssue("semantic", code, file, message)]);
}
function projectRuntimeOwnsRun(projectRoot, runId, env) {
const path = kxmProjectRunEventsPath(projectRoot, env);
if (!existsSync7(path)) return false;
const database = openReadOnlyDatabase(path);
try {
database.exec("PRAGMA busy_timeout = 5000");
return database.prepare("SELECT 1 FROM runs WHERE run_id = ?").get(runId) !== void 0;
} finally {
database.close();
}
}
var KXM_REGISTRY_SCHEMA_VERSION = 2;
var REGISTRY_TABLES = {
supervisor: ["singleton_id", "runtime_id", "pid", "port", "token_hash", "started_at", "heartbeat_at", "state"],
projects: ["project_id", "project_root", "project_key", "home_runtime_id", "config_revision", "registered_at", "lane_of"]
};
var REGISTRY_SCHEMA = `
CREATE TABLE supervisor (
singleton_id INTEGER PRIMARY KEY CHECK (singleton_id = 1),
runtime_id TEXT NOT NULL,
pid INTEGER NOT NULL,
port INTEGER NOT NULL,
token_hash TEXT NOT NULL,
started_at TEXT NOT NULL,
heartbeat_at TEXT NOT NULL,
state TEXT NOT NULL
) STRICT;
CREATE TABLE projects (
project_key TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
project_root TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
config_revision TEXT,
registered_at TEXT NOT NULL,
lane_of TEXT
) STRICT;
CREATE INDEX projects_by_project_id ON projects (project_id);
`;
var PROJECT_COLUMNS = "project_id, project_root, project_key, home_runtime_id, config_revision, registered_at, lane_of";
function registrationFromRow(row) {
return {
projectId: row.project_id,
projectRoot: row.project_root,
projectKey: row.project_key,
homeRuntimeId: row.home_runtime_id,
...row.config_revision !== null ? { configRevision: row.config_revision } : {},
...row.lane_of !== null ? { laneOf: row.lane_of } : {},
registeredAt: row.registered_at
};
}
function controlRootDirectoryExists(projectRoot) {
const stat = statSync(projectRoot, { throwIfNoEntry: false });
return Boolean(stat?.isDirectory());
}
function gitEnv() {
return Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.toUpperCase().startsWith("GIT_")));
}
function gitCommonDirectory(projectRoot) {
const result = spawnSync3("git", ["-C", projectRoot, "rev-parse", "--git-common-dir"], {
encoding: "utf8",
env: gitEnv(),
timeout: 3e4,
windowsHide: true
});
if (result.status !== 0) return void 0;
const text = (result.stdout ?? "").trim();
if (!text) return void 0;
const absolute = isAbsolute4(text) ? text : resolve6(projectRoot, text);
let canonical;
try {
canonical = realpathSync3.native(absolute);
} catch {
canonical = resolve6(absolute);
}
return process.platform === "win32" ? canonical.toLocaleLowerCase("en-US") : canonical;
}
function isPrimaryWorktree(projectRoot, commonDir) {
if (commonDir === void 0) return false;
const dotGit = resolve6(projectRoot, ".git");
let canonical;
try {
canonical = realpathSync3.native(dotGit);
} catch {
canonical = resolve6(dotGit);
}
if (process.platform === "win32") canonical = canonical.toLocaleLowerCase("en-US");
return canonical === commonDir;
}
function migrateRegistryLanes(file) {
const stat = lstatSync3(file, { throwIfNoEntry: false });
if (!stat) return;
assertDatabaseFile(file, "runtime registry");
const database = new DatabaseSync(file);
let transaction = false;
try {
database.exec("PRAGMA busy_timeout = 5000");
const current = database.prepare("PRAGMA user_version").get();
if ((current?.user_version ?? 0) !== 1) return;
database.exec("BEGIN IMMEDIATE");
transaction = true;
const locked = database.prepare("PRAGMA user_version").get();
if ((locked?.user_version ?? 0) !== 1) {
database.exec("ROLLBACK");
transaction = false;
return;
}
if (!tableColumns(database, "projects").includes("lane_of")) {
database.exec(`
CREATE TABLE projects_v2 (
project_key TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
project_root TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
config_revision TEXT,
registered_at TEXT NOT NULL,
lane_of TEXT
) STRICT;
INSERT INTO projects_v2 (project_key, project_id, project_root, home_runtime_id, config_revision, registered_at, lane_of)
SELECT project_key, project_id, project_root, home_runtime_id, config_revision, registered_at, NULL FROM projects;
DROP TABLE projects;
ALTER TABLE projects_v2 RENAME TO projects;
CREATE INDEX projects_by_project_id ON projects (project_id);
`);
}
database.exec("PRAGMA user_version = 2");
database.exec("COMMIT");
transaction = false;
} catch (error) {
if (transaction) {
try {
database.exec("ROLLBACK");
} catch {
}
}
throw error;
} finally {
database.close();
}
}
function readKxmSupervisorRecord(database) {
const row = database.prepare("SELECT runtime_id, pid, port, token_hash, started_at, heartbeat_at, state FROM supervisor WHERE singleton_id = 1").get();
return row ? {
runtimeId: row.runtime_id,
pid: row.pid,
port: row.port,
tokenHash: row.token_hash,
startedAt: row.started_at,
heartbeatAt: row.heartbeat_at,
state: row.state
} : void 0;
}
var KxmRuntimeRegistry = class {
path;
database;
constructor(path) {
this.path = resolve6(path);
migrateRegistryLanes(this.path);
this.database = openDatabase(this.path, "runtime registry", {
schema: REGISTRY_SCHEMA,
version: KXM_REGISTRY_SCHEMA_VERSION,
tables: REGISTRY_TABLES
});
}
close() {
this.database.close();
}
/** Atomically claim or refresh the supervisor singleton. Returns the record that now owns it. */
claimSupervisor(record2) {
this.database.exec("BEGIN IMMEDIATE");
try {
const existing = this.readSupervisorRow();
if (!existing) {
this.database.prepare(`
INSERT INTO supervisor (singleton_id, runtime_id, pid, port, token_hash, started_at, heartbeat_at, state)
VALUES (1, ?, ?, ?, ?, ?, ?, 'running')
`).run(record2.runtimeId, record2.pid, record2.port, record2.tokenHash, record2.now, record2.now);
this.database.exec("COMMIT");
return { claimed: true, record: this.supervisor() };
}
if (existing.runtimeId === record2.runtimeId && existing.pid === record2.pid) {
this.database.prepare("UPDATE supervisor SET heartbeat_at = ?, state = 'running' WHERE singleton_id = 1").run(record2.now);
this.database.exec("COMMIT");
return { claimed: true, record: this.supervisor() };
}
this.database.exec("ROLLBACK");
return { claimed: false, record: existing };
} catch (error) {
try {
this.database.exec("ROLLBACK");
} catch {
}
throw error;
}
}
/** Take over a dead supervisor's singleton, preserving its logical runtime identity and project home bindings. */
takeoverSupervisor(record2) {
this.database.exec("BEGIN IMMEDIATE");
try {
const existing = this.readSupervisorRow();
const runtimeId = existing?.runtimeId ?? record2.runtimeId;
const updated = this.database.prepare(`
UPDATE supervisor
SET runtime_id = ?, pid = ?, port = ?, token_hash = ?, started_at = ?, heartbeat_at = ?, state = 'running'
WHERE singleton_id = 1 AND pid = ? AND heartbeat_at = ?
`).run(runtimeId, record2.pid, record2.port, record2.tokenHash, record2.now, record2.now, record2.observedDeadPid, record2.observedHeartbeatAt);
if (updated.changes !== 1) {
this.database.exec("ROLLBACK");
throw runtimeError("runtime_supervisor_conflict", "supervisor", "another process claimed the supervisor singleton first");
}
this.database.exec("COMMIT");
return this.supervisor();
} catch (error) {
try {
this.database.exec("ROLLBACK");
} catch {
}
throw error;
}
}
markStopping(pid, now) {
this.database.prepare("UPDATE supervisor SET state = 'stopping', heartbeat_at = ? WHERE singleton_id = 1 AND pid = ?").run(now, pid);
}
markStopped(pid, now) {
this.database.prepare("UPDATE supervisor SET state = 'stopped', heartbeat_at = ? WHERE singleton_id = 1 AND pid = ?").run(now, pid);
}
heartbeat(pid, now) {
const result = this.database.prepare("UPDATE supervisor SET heartbeat_at = ? WHERE singleton_id = 1 AND pid = ?").run(now, pid);
return Number(result.changes);
}
readSupervisorRow() {
return readKxmSupervisorRecord(this.database);
}
supervisor() {
return this.readSupervisorRow();
}
/** All projects registered to this Runtime, including lane roots, for restart
* recovery: the supervisor reopens their contexts so pending outbox rows
* resume syncing and presence keeps beating. */
projectsForRuntime(homeRuntimeId) {
const rows = this.database.prepare(
"SELECT project_root, project_id FROM projects WHERE home_runtime_id = ? ORDER BY registered_at"
).all(homeRuntimeId);
return rows.map((row) => ({ projectRoot: row.project_root, projectId: row.project_id }));
}
/**
* Register or revalidate a control root. The home runtime of a live row is
* immutable. A second root whose git common directory matches a live row
* for the same project is a lane, unless the registering root is the primary
* worktree and the live home row is not: then the primary becomes the home
* row (same home runtime id) and every other live row of that repository
* becomes its lane. A primary never becomes a lane. A root whose directory
* is gone is replaced. A live root that is a different repository is
* `project_home_conflict`.
*/
registerProject(registration) {
const projectRoot = resolve6(registration.projectRoot);
const projectKey = projectRuntimeKey(projectRoot);
const candidateCommon = gitCommonDirectory(projectRoot);
const commonByRoot = /* @__PURE__ */ new Map();
for (let attempt = 0; attempt < 8; attempt += 1) {
this.database.exec("BEGIN IMMEDIATE");
let rootsToMeasure;
try {
const byKey = this.projectRow("SELECT " + PROJECT_COLUMNS + " FROM projects WHERE project_key = ?", projectKey);
if (byKey) {
const problems = [];
if (byKey.project_id !== registration.projectId) problems.push(`control root is already bound to a different project id ${byKey.project_id}`);
if (byKey.home_runtime_id !== registration.homeRuntimeId) problems.push(`project ${registration.projectId} home runtime is immutable and cannot be rebound`);
if (problems.length > 0) {
this.database.exec("ROLLBACK");
throw runtimeError("project_home_conflict", ".kxm/project.yaml", problems.join("; "));
}
const result = registrationFromRow(byKey);
this.database.exec("COMMIT");
return result;
}
const rows = this.database.prepare(
`SELECT ${PROJECT_COLUMNS} FROM projects WHERE project_id = ? ORDER BY registered_at`
).all(registration.projectId);
const live = rows.filter((row) => controlRootDirectoryExists(row.project_root));
const dead = rows.filter((row) => !controlRootDirectoryExists(row.project_root));
const unknown = live.filter((row) => !commonByRoot.has(row.project_root));
if (unknown.length > 0) {
rootsToMeasure = unknown.map((row) => row.project_root);
this.database.exec("ROLLBACK");
} else if (live.length > 0) {
const anchor = live.find((row) => {
const dir = commonByRoot.get(row.project_root);
return candidateCommon !== void 0 && dir === candidateCommon;
});
if (!anchor) {
this.database.exec("ROLLBACK");
throw runtimeError(
"project_home_conflict",
".kxm/project.yaml",
`project ${registration.projectId} is already bound to a different control root`
);
}
if (live.some((row) => row.home_runtime_id !== registration.homeRuntimeId)) {
this.database.exec("ROLLBACK");
throw runtimeError(
"project_home_conflict",
".kxm/project.yaml",
`project ${registration.projectId} home runtime is immutable and cannot be rebound`
);
}
const sameRepo = live.filter((row) => commonByRoot.get(row.project_root) === candidateCommon);
const home = sameRepo.find((row) => row.lane_of === null);
const registeringIsPrimary = isPrimaryWorktree(projectRoot, candidateCommon);
const homeIsPrimary = home !== void 0 && isPrimaryWorktree(home.project_root, commonByRoot.get(home.project_root));
if (registeringIsPrimary && !homeIsPrimary) {
this.insertHome(registration, projectRoot, projectKey);
for (const row of sameRepo) {
this.database.prepare("UPDATE projects SET lane_of = ? WHERE project_key = ?").run(projectKey, row.project_key);
}
this.database.exec("COMMIT");
registration.logger?.({
event: "project_home_promoted",
projectId: registration.projectId,
projectRoot,
homeRuntimeId: registration.homeRuntimeId,
previousHomeRoot: home?.project_root ?? null,
previousHomeKey: home?.project_key ?? null
});
return this.insertedRegistration(registration, projectRoot, projectKey);
}
if (registeringIsPrimary) {
this.database.exec("ROLLBACK");
throw runtimeError(
"project_home_conflict",
".kxm/project.yaml",
`project ${registration.projectId} primary checkout is already the home row`
);
}
const laneOf = anchor.lane_of ?? anchor.project_key;
this.database.prepare(`
INSERT INTO projects (project_key, project_id, project_root, home_runtime_id, config_revision, registered_at, lane_of)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).run(projectKey, registration.projectId, projectRoot, registration.homeRuntimeId, registration.configRevision ?? null, registration.now, laneOf);
const result = this.insertedRegistration(registration, projectRoot, projectKey, laneOf);
this.database.exec("COMMIT");
return result;
} else if (dead.length > 0) {
const replaced = dead[0];
if (dead.some((row) => row.home_runtime_id !== registration.homeRuntimeId)) {
this.database.exec("ROLLBACK");
throw runtimeError(
"project_home_conflict",
".kxm/project.yaml",
`project ${registration.projectId} home runtime is immutable and cannot be rebound`
);
}
this.database.prepare("DELETE FROM projects WHERE project_id = ?").run(registration.projectId);
this.insertHome(registration, projectRoot, projectKey);
this.database.exec("COMMIT");
registration.logger?.({
event: "project_registration_replaced",
projectId: registration.projectId,
projectRoot,
replacedRoot: replaced.project_root,
replacedCount: dead.length,
replacedHomeRuntimeId: replaced.home_runtime_id,
replacedProjectKey: replaced.project_key
});
return this.insertedRegistration(registration, projectRoot, projectKey);
} else {
this.insertHome(registration, projectRoot, projectKey);
this.database.exec("COMMIT");
return this.insertedRegistration(registration, projectRoot, projectKey);
}
} catch (error) {
try {
this.database.exec("ROLLBACK");
} catch {
}
throw error;
}
for (const root of rootsToMeasure ?? []) {
commonByRoot.set(root, gitCommonDirectory(root));
}
}
throw runtimeError(
"runtime_registry_busy",
projectRoot,
`project ${registration.projectId} registration could not be rechecked`
);
}
/** Remove one control root. Returns false when that root was not registered. */
unregisterProject(projectRoot) {
this.database.exec("BEGIN IMMEDIATE");
try {
const removed = this.deleteRegisteredRoot(projectRoot);
this.database.exec("COMMIT");
return removed;
} catch (error) {
try {
this.database.exec("ROLLBACK");
} catch {
}
throw error;
}
}
/**
* Delete the row only when `supervisorIsLive` is false for the supervisor
* row read inside this write transaction. A live supervisor keeps the row;
* the caller uses the supervisor route instead of editing the file.
*/
unregisterProjectIfIdle(projectRoot, supervisorIsLive) {
this.database.exec("BEGIN IMMEDIATE");
try {
if (supervisorIsLive(this.readSupervisorRow())) {
this.database.exec("ROLLBACK");
return "supervisor_live";
}
const removed = this.deleteRegisteredRoot(projectRoot);
this.database.exec("COMMIT");
return removed ? "removed" : "absent";
} catch (error) {
try {
this.database.exec("ROLLBACK");
} catch {
}
throw error;
}
}
/** How many other rows share this home root's project. Zero when this root is a lane or missing. */
homeLaneCount(projectRoot) {
const row = this.projectRow(`SELECT ${PROJECT_COLUMNS} FROM projects WHERE project_key = ?`, projectRuntimeKey(resolve6(projectRoot)));
if (!row || row.lane_of !== null) return 0;
const count = this.database.prepare(
"SELECT COUNT(*) AS total FROM projects WHERE project_id = ? AND project_key != ?"
).get(row.project_id, row.project_key);
return Number(count?.total ?? 0);
}
/** Caller holds the write transaction. Does not commit. */
deleteRegisteredRoot(projectRoot) {
const projectKey = projectRuntimeKey(resolve6(projectRoot));
const row = this.projectRow(`SELECT ${PROJECT_COLUMNS} FROM projects WHERE project_key = ?`, projectKey);
if (!row) return false;
this.database.prepare("DELETE FROM projects WHERE project_key = ?").run(projectKey);
if (row.lane_of === null) {
const successor = this.database.prepare(
"SELECT project_key FROM projects WHERE project_id = ? ORDER BY registered_at LIMIT 1"
).get(row.project_id);
if (successor) {
this.database.prepare("UPDATE projects SET lane_of = NULL WHERE project_key = ?").run(successor.project_key);
this.database.prepare(
"UPDATE projects SET lane_of = ? WHERE project_id = ? AND project_key != ? AND (lane_of IS NULL OR lane_of = ?)"
).run(successor.project_key, row.project_id, successor.project_key, projectKey);
}
}
return true;
}
/** The home row for a project id, or the earliest row when every row is a lane. */
project(projectId) {
const row = this.projectRow(
`SELECT ${PROJECT_COLUMNS} FROM projects WHERE project_id = ? ORDER BY CASE WHEN lane_of IS NULL THEN 0 ELSE 1 END, registered_at LIMIT 1`,
projectId
);
return row ? registrationFromRow(row) : void 0;
}
projectByRoot(projectRoot) {
const row = this.projectRow(`SELECT ${PROJECT_COLUMNS} FROM projects WHERE project_key = ?`, projectRuntimeKey(projectRoot));
return row ? registrationFromRow(row) : void 0;
}
projectRow(sql, parameter) {
return this.database.prepare(sql).get(parameter);
}
insertHome(registration, projectRoot, projectKey) {
this.database.prepare(`
INSERT INTO projects (project_key, project_id, project_root, home_runtime_id, config_revision, registered_at, lane_of)
VALUES (?, ?, ?, ?, ?, ?, NULL)
`).run(projectKey, registration.projectId, projectRoot, registration.homeRuntimeId, registration.configRevision ?? null, registration.now);
}
insertedRegistration(registration, projectRoot, projectKey, laneOf) {
return {
projectId: registration.projectId,
projectRoot,
projectKey,
homeRuntimeId: registration.homeRuntimeId,
...registration.configRevision !== void 0 ? { configRevision: registration.configRevision } : {},
...laneOf !== void 0 ? { laneOf } : {},
registeredAt: registration.now
};
}
};
var KXM_RUN_EVENT_SCHEMA = "kxm.run-event.v1";
var KXM_ABSENT_MEMORY_REVISION = "ctxrev_absent";
function hashKxmDriveLog(events) {
const body = events.map((event) => `${event.eventId}:${event.sequence}`).join("\n");
return `sha256:${createHash7("sha256").update(body, "utf8").digest("hex")}`;
}
function verifyKxmDriveReceipt(receipt, events, foldedStatus, binding) {
const reasons = [];
if (receipt.runId !== binding.runId) {
reasons.push(`runId ${receipt.runId} != binding ${binding.runId}`);
}
if (receipt.driveId !== binding.driveId) {
reasons.push(`driveId ${receipt.driveId} != binding ${binding.driveId}`);
}
const last = events[events.length - 1];
const currentLast = last?.sequence ?? 0;
if (receipt.lastSequence !== currentLast) {
reasons.push(`lastSequence ${receipt.lastSequence} != log ${currentLast}`);
}
const prefix = events.filter((event) => event.sequence >= 1 && event.sequence <= receipt.lastSequence);
if (hashKxmDriveLog(prefix) !== receipt.logHash) {
reasons.push("logHash mismatch");
}
if (receipt.settlement.status !== foldedStatus) {
reasons.push(`settlement.status ${receipt.settlement.status} != folded ${foldedStatus}`);
}
if (reasons.length === 0) return { verified: true };
return { verified: false, divergence: reasons.join("; ") };
}
var KXM_EVENT_STORE_SCHEMA_VERSION = 7;
var KXM_DRIVE_RECEIPT_SCHEMA = "kxm.drive-receipt.v1";
var DRIVE_RECEIPT_MAX_BYTES = 8 * 1024;
var EVENT_STORE_TABLES = {
runs: ["run_id", "project_id", "home_runtime_id", "workflow_id", "prompt_sha256", "status", "config_revision", "memory_revision", "executor_policy_revision", "tool_policy_revision", "created_at", "updated_at"],
events: ["project_id", "run_id", "sequence", "event_id", "event_type", "command_id", "occurred_at", "recorded_at", "monotonic_ns", "config_revision", "memory_revision", "executor_policy_revision", "tool_policy_revision", "payload", "schema", "home_runtime_id"],
commands: ["command_id", "run_id", "kind", "result", "recorded_at"],
run_plans: ["run_id", "run_plan_hash", "envelope", "pinned_sequence"],
run_state: ["run_id", "last_sequence", "state"],
attempt_capabilities: ["attempt_id", "run_id", "assignment_id", "step_id", "step_attempt", "producer_id", "capability_hash", "state"],
gate_attempts: [
"attempt_id",
"run_id",
"project_id",
"home_runtime_id",
"step_id",
"step_attempt",
"assignment_id",
"effect_id",
"gate_id",
"gate_kind",
"expect",
"gate_definition_hash",
"registry_hash",
"run_plan_hash",
"control_project_key",
"producer_id",
"intent_event_id",
"content_hash"
],
gate_observations: [
"observation_id",
"attempt_id",
"run_id",
"project_id",
"home_runtime_id",
"step_id",
"step_attempt",
"assignment_id",
"effect_id",
"completeness",
"spawned",
"pid",
"exit_code",
"signal",
"exit_observed",
"close_observed",
"stop_cause",
"signals_attempted",
"error_class",
"stdout_sha256",
"stdout_bytes",
"stdout_complete",
"stderr_sha256",
"stderr_bytes",
"stderr_complete",
"checked_count",
"failed_count",
"elapsed_ms",
"started_at",
"finished_at",
"recorded_event_id",
"content_hash"
],
gate_evidence: [
"evidence_id",
"attempt_id",
"observation_id",
"run_id",
"project_id",
"home_runtime_id",
"step_id",
"step_attempt",
"assignment_id",
"effect_id",
"evidence_key",
"kind",
"expect",
"outcome",
"settled_event_id",
"content_hash"
],
drive_receipts: ["drive_id", "run_id", "project_id", "opened_sequence", "last_sequence", "closed_at", "schema", "receipt"],
coordinators: [
"coordinator_id",
"project_id",
"role",
"channel",
"ceiling_hash",
"config_revision",
"bound_at",
"schema",
"record"
],
intake_messages: [
"message_id",
"project_id",
"coordinator_id",
"idempotency_key",
"content_hash",
"received_at",
"dispatch_state",
"schema",
"record"
],
project_controls: ["project_id", "paused", "reason", "updated_at", "actor", "schema", "record"],
outbox: [
"seq",
"run_id",
"sequence",
"sync_event",
"attempted_at",
"attempt_count",
"acked_at",
"refused_code",
"refused_at"
]
};
var KXM_EVENT_STORE_TABLE_NAMES = Object.keys(EVENT_STORE_TABLES).sort();
var EVENT_STORE_SCHEMA = `
CREATE TABLE runs (
run_id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
workflow_id TEXT NOT NULL,
prompt_sha256 TEXT NOT NULL,
status TEXT NOT NULL,
config_revision TEXT NOT NULL,
memory_revision TEXT NOT NULL,
executor_policy_revision TEXT NOT NULL,
tool_policy_revision TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
) STRICT;
CREATE TABLE events (
project_id TEXT NOT NULL,
run_id TEXT NOT NULL,
sequence INTEGER NOT NULL,
event_id TEXT NOT NULL UNIQUE,
event_type TEXT NOT NULL,
command_id TEXT,
occurred_at TEXT NOT NULL,
recorded_at TEXT NOT NULL,
monotonic_ns TEXT NOT NULL,
config_revision TEXT NOT NULL,
memory_revision TEXT NOT NULL,
executor_policy_revision TEXT NOT NULL,
tool_policy_revision TEXT NOT NULL,
payload TEXT NOT NULL,
schema TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
PRIMARY KEY (project_id, run_id, sequence)
) STRICT;
CREATE INDEX events_run ON events(run_id, sequence);
CREATE TABLE commands (
command_id TEXT PRIMARY KEY,
run_id TEXT NOT NULL,
kind TEXT NOT NULL,
result TEXT NOT NULL,
recorded_at TEXT NOT NULL
) STRICT;
CREATE TABLE run_plans (
run_id TEXT PRIMARY KEY REFERENCES runs(run_id),
run_plan_hash TEXT NOT NULL,
envelope TEXT NOT NULL,
pinned_sequence INTEGER NOT NULL
) STRICT;
CREATE TABLE run_state (
run_id TEXT PRIMARY KEY REFERENCES runs(run_id),
last_sequence INTEGER NOT NULL,
state TEXT NOT NULL
) STRICT;
CREATE TABLE attempt_capabilities (
attempt_id TEXT PRIMARY KEY,
run_id TEXT NOT NULL,
assignment_id TEXT NOT NULL,
step_id TEXT NOT NULL,
step_attempt INTEGER NOT NULL,
producer_id TEXT NOT NULL,
capability_hash TEXT NOT NULL UNIQUE,
state TEXT NOT NULL CHECK (state IN ('issued','settled','revoked'))
) STRICT;
CREATE TABLE gate_attempts (
attempt_id TEXT PRIMARY KEY REFERENCES attempt_capabilities(attempt_id),
run_id TEXT NOT NULL REFERENCES runs(run_id),
project_id TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
step_id TEXT NOT NULL,
step_attempt INTEGER NOT NULL,
assignment_id TEXT NOT NULL,
effect_id TEXT NOT NULL UNIQUE,
gate_id TEXT NOT NULL,
gate_kind TEXT NOT NULL CHECK (gate_kind IN ('command','artifacts-exist')),
expect TEXT NOT NULL CHECK (expect IN ('pass','fail')),
gate_definition_hash TEXT NOT NULL,
registry_hash TEXT NOT NULL,
run_plan_hash TEXT NOT NULL,
control_project_key TEXT NOT NULL,
producer_id TEXT NOT NULL CHECK (producer_id = 'kxm-gate'),
intent_event_id TEXT NOT NULL UNIQUE REFERENCES events(event_id),
content_hash TEXT NOT NULL
) STRICT;
CREATE INDEX gate_attempts_run ON gate_attempts(run_id);
CREATE INDEX gate_attempts_project ON gate_attempts(project_id);
CREATE TABLE gate_observations (
observation_id TEXT PRIMARY KEY,
attempt_id TEXT NOT NULL UNIQUE REFERENCES gate_attempts(attempt_id),
run_id TEXT NOT NULL REFERENCES runs(run_id),
project_id TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
step_id TEXT NOT NULL,
step_attempt INTEGER NOT NULL,
assignment_id TEXT NOT NULL,
effect_id TEXT NOT NULL,
completeness TEXT NOT NULL CHECK (completeness IN ('complete','incomplete','no-start')),
spawned INTEGER NOT NULL CHECK (spawned IN (0, 1)),
pid INTEGER,
exit_code INTEGER,
signal TEXT,
exit_observed INTEGER NOT NULL CHECK (exit_observed IN (0, 1)),
close_observed INTEGER NOT NULL CHECK (close_observed IN (0, 1)),
stop_cause TEXT NOT NULL CHECK (stop_cause IN ('none','timeout','cancel','error')),
signals_attempted TEXT NOT NULL CHECK (signals_attempted IN ('none','term','term-kill')),
error_class TEXT CHECK (error_class IN ('validation','spawn-error','stream-error','stop-error','recording-error','lost-close')),
stdout_sha256 TEXT,
stdout_bytes INTEGER,
stdout_complete INTEGER CHECK (stdout_complete IN (0, 1)),
stderr_sha256 TEXT,
stderr_bytes INTEGER,
stderr_complete INTEGER CHECK (stderr_complete IN (0, 1)),
checked_count INTEGER,
failed_count INTEGER,
elapsed_ms INTEGER NOT NULL,
started_at TEXT NOT NULL,
finished_at TEXT,
recorded_event_id TEXT NOT NULL UNIQUE REFERENCES events(event_id),
content_hash TEXT NOT NULL
) STRICT;
CREATE INDEX gate_observations_run ON gate_observations(run_id);
CREATE TABLE gate_evidence (
evidence_id TEXT PRIMARY KEY,
attempt_id TEXT NOT NULL UNIQUE REFERENCES gate_attempts(attempt_id),
observation_id TEXT NOT NULL UNIQUE REFERENCES gate_observations(observation_id),
run_id TEXT NOT NULL REFERENCES runs(run_id),
project_id TEXT NOT NULL,
home_runtime_id TEXT NOT NULL,
step_id TEXT NOT NULL,
step_attempt INTEGER NOT NULL,
assignment_id TEXT NOT NULL,
effect_id TEXT NOT NULL,
evidence_key TEXT,
kind TEXT NOT NULL CHECK (kind = 'gate'),
expect TEXT NOT NULL CHECK (expect IN ('pass','fail')),
outcome TEXT NOT NULL CHECK (outcome IN ('passed','implementation-failure','repro-missing')),
settled_event_id TEXT NOT NULL UNIQUE REFERENCES events(event_id),
content_hash TEXT NOT NULL
) STRICT;
CREATE UNIQUE INDEX gate_evidence_key ON gate_evidence(run_id, step_id, step_attempt, evidence_key) WHERE evidence_key IS NOT NULL;
CREATE INDEX gate_evidence_run ON gate_evidence(run_id);
CREATE TABLE drive_receipts (
drive_id TEXT PRIMARY KEY,
run_id TEXT NOT NULL,
project_id TEXT NOT NULL,
opened_sequence INTEGER NOT NULL,
last_sequence INTEGER NOT NULL,
closed_at TEXT NOT NULL,
schema TEXT NOT NULL,
receipt TEXT NOT NULL
) STRICT;
CREATE INDEX drive_receipts_run ON drive_receipts(run_id);
CREATE TABLE coordinators (
coordinator_id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
role TEXT NOT NULL,
channel TEXT NOT NULL,
ceiling_hash TEXT NOT NULL,
config_revision TEXT NOT NULL,
bound_at TEXT NOT NULL,
schema TEXT NOT NULL,
record TEXT NOT NULL
) STRICT;
CREATE UNIQUE INDEX coordinators_slot ON coordinators(project_id, role, channel);
CREATE TABLE intake_messages (
message_id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
coordinator_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
content_hash TEXT NOT NULL,
received_at TEXT NOT NULL,
dispatch_state TEXT NOT NULL CHECK (dispatch_state IN ('ready','held_paused','admitted','refused')),
schema TEXT NOT NULL,
record TEXT NOT NULL
) STRICT;
CREATE UNIQUE INDEX intake_idempotency ON intake_messages(project_id, coordinator_id, idempotency_key);
CREATE INDEX intake_dispatch ON intake_messages(project_id, dispatch_state, received_at, message_id);
CREATE TABLE project_controls (
project_id TEXT PRIMARY KEY,
paused INTEGER NOT NULL CHECK (paused IN (0, 1)),
reason TEXT,
updated_at TEXT NOT NULL,
actor TEXT NOT NULL,
schema TEXT NOT NULL,
record TEXT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS outbox (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
run_id TEXT NOT NULL,
sequence INTEGER NOT NULL,
sync_event TEXT NOT NULL,
attempted_at TEXT,
attempt_count INTEGER NOT NULL DEFAULT 0,
acked_at TEXT,
refused_code TEXT,
refused_at TEXT,
UNIQUE (run_id, sequence)
) STRICT;
CREATE INDEX outbox_pending ON outbox(seq) WHERE acked_at IS NULL AND refused_code IS NULL;
CREATE INDEX outbox_refused ON outbox(seq) WHERE refused_code IS NOT NULL;
`;
var KxmRunEventStore = class {
path;
/** Secret values registered here are replaced in every sync object this
* store derives. In memory only: they are never written anywhere. */
syncRedactor = new KxmSyncRedactor();
database;
constructor(path) {
this.path = resolve6(path);
this.database = openDatabase(this.path, "run event store", {
schema: EVENT_STORE_SCHEMA,
version: KXM_EVENT_STORE_SCHEMA_VERSION,
tables: EVENT_STORE_TABLES
});
}
close() {
this.database.close();
}
/** Persist the accepted prompt outside the event log (hashed in events only). */
putRunPrompt(runId, prompt) {
const all = this.readRunPrompts();
all[runId] = prompt;
this.writeRunPrompts(all);
}
getRunPrompt(runId) {
const value = this.readRunPrompts()[runId];
return typeof value === "string" ? value : void 0;
}
runPromptSidecarPath() {
return `${this.path}.run-prompts.json`;
}
readRunPrompts() {
const sidecar = this.runPromptSidecarPath();
if (!existsSync7(sidecar)) return {};
try {
const parsed = JSON.parse(readFileSync4(sidecar, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
return Object.fromEntries(
Object.entries(parsed).filter((entry) => typeof entry[1] === "string")
);
} catch {
return {};
}
}
writeRunPrompts(all) {
writeFileSync2(this.runPromptSidecarPath(), `${JSON.stringify(all)}
`, { encoding: "utf8", mode: 384 });
}
/** Run one immutable transaction, rolling back on any failure. */
transaction(work) {
return withDatabaseTransaction(this.database, work);
}
command(commandId) {
const row = this.database.prepare("SELECT command_id, run_id, kind, result, recorded_at FROM commands WHERE command_id = ?").get(commandId);
return row ? { commandId: row.command_id, runId: row.run_id, kind: row.kind, result: JSON.parse(row.result), recordedAt: row.recorded_at } : void 0;
}
insertCommand(record2) {
this.database.prepare("INSERT INTO commands (command_id, run_id, kind, result, recorded_at) VALUES (?, ?, ?, ?, ?)").run(record2.commandId, record2.runId, record2.kind, JSON.stringify(record2.result), record2.recordedAt);
}
insertRun(record2) {
this.database.prepare(`
INSERT INTO runs (run_id, project_id, home_runtime_id, workflow_id, prompt_sha256, status, config_revision, memory_revision, executor_policy_revision, tool_policy_revision, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
record2.runId,
record2.projectId,
record2.homeRuntimeId,
record2.workflowId,
record2.promptSha256,
record2.status,
record2.configRevision,
record2.memoryRevision,
record2.executorPolicyRevision,
record2.toolPolicyRevision,
record2.createdAt,
record2.updatedAt
);
}
updateRunStatus(runId, status, updatedAt) {
this.database.prepare("UPDATE runs SET status = ?, updated_at = ? WHERE run_id = ?").run(status, updatedAt, runId);
}
run(runId) {
const row = this.database.prepare(`
SELECT run_id, project_id, home_runtime_id, workflow_id, prompt_sha256, status, config_revision, memory_revision, executor_policy_revision, tool_policy_revision, created_at, updated_at
FROM runs WHERE run_id = ?
`).get(runId);
return row ? runFromRow(row) : void 0;
}
/** All projects registered to this Runtime, for restart recovery: the
* supervisor needs to reopen their contexts so pending outbox rows resume
* syncing and presence keeps beating. */
projectsForRuntime(homeRuntimeId) {
const rows = this.database.prepare(
"SELECT project_root, project_id FROM projects WHERE home_runtime_id = ? ORDER BY registered_at"
).all(homeRuntimeId);
return rows.map((row) => ({ projectRoot: row.project_root, projectId: row.project_id }));
}
runsForProject(projectId, limit = 50) {
const rows = this.database.prepare(`
SELECT run_id, project_id, home_runtime_id, workflow_id, prompt_sha256, status, config_revision, memory_revision, executor_policy_revision, tool_policy_revision, created_at, updated_at
FROM runs WHERE project_id = ? ORDER BY created_at DESC, run_id DESC LIMIT ?
`).all(projectId, limit);
return rows.map(runFromRow);
}
nextSequence(runId) {
const row = this.database.prepare("SELECT COALESCE(MAX(sequence), 0) AS max_sequence FROM events WHERE run_id = ?").get(runId);
return row.max_sequence + 1;
}
appendEvent(event) {
validateRunEvent(event, "run-event");
const run = this.run(event.runId);
if (!run) throw runtimeError("run_unknown", event.runId, "run does not exist in this event store");
if (event.homeRuntimeId !== run.homeRuntimeId || event.projectId !== run.projectId) {
throw runtimeError("run_event_owner_mismatch", event.runId, "event homeRuntimeId or projectId does not match the run");
}
this.database.prepare(`
INSERT INTO events (project_id, run_id, sequence, event_id, event_type, command_id, occurred_at, recorded_at, monotonic_ns, config_revision, memory_revision, executor_policy_revision, tool_policy_revision, payload, schema, home_runtime_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
event.projectId,
event.runId,
event.sequence,
event.eventId,
event.eventType,
event.commandId ?? null,
event.occurredAt,
event.recordedAt,
event.monotonicNs,
event.configRevision,
event.memoryRevision,
event.executorPolicyRevision,
event.toolPolicyRevision,
JSON.stringify(event.payload),
event.schema,
event.homeRuntimeId
);
const syncEvent = deriveKxmSyncEvent(event, { redactor: this.syncRedactor });
this.database.prepare("INSERT INTO outbox (run_id, sequence, sync_event) VALUES (?, ?, ?)").run(event.runId, event.sequence, kxmSyncEventBytes(syncEvent));
}
/**
* Retryable outbox rows after `afterSeq`, in outbox order, oldest first.
* Acked and durably refused rows are never returned: a refused row is not
* waiting for a retry, it is waiting for an operator.
*/
pendingOutbox(limit = 100, afterSeq = 0) {
const rows = this.database.prepare(`
SELECT seq, run_id, sequence, sync_event, attempt_count, attempted_at, acked_at, refused_code, refused_at
FROM outbox WHERE acked_at IS NULL AND refused_code IS NULL AND seq > ? ORDER BY seq ASC LIMIT ?
`).all(afterSeq, limit);
return rows.map(outboxFromRow);
}
/** Every outbox row of one run, in any state, in sequence order. */
outboxForRun(runId) {
const rows = this.database.prepare(`
SELECT seq, run_id, sequence, sync_event, attempt_count, attempted_at, acked_at, refused_code, refused_at
FROM outbox WHERE run_id = ? ORDER BY sequence ASC
`).all(runId);
return rows.map(outboxFromRow);
}
/**
* Count one attempt against each row. Refused rows are never re-counted: they
* are out of the queue, and a tick that reaches them again would mean the
* refusal was cleared (which resets the count).
*/
markOutboxAttempted(seqs, at) {
const statement = this.database.prepare(`
UPDATE outbox SET attempted_at = ?, attempt_count = attempt_count + 1
WHERE seq = ? AND acked_at IS NULL AND refused_code IS NULL
`);
this.transaction(() => {
for (const seq of seqs) statement.run(at, seq);
});
}
/** Advance the cursor: the hub holds these rows now. Returns rows newly acked. */
ackOutbox(seqs, at) {
const statement = this.database.prepare("UPDATE outbox SET acked_at = ?, refused_code = NULL, refused_at = NULL WHERE seq = ? AND acked_at IS NULL");
return this.transaction(() => {
let changed = 0;
for (const seq of seqs) changed += Number(statement.run(at, seq).changes);
return changed;
});
}
/**
* Record a durable hub refusal: the answer will not change if the same bytes
* are sent again. Returns rows newly moved out of the pending queue.
*/
refuseOutbox(refusals, at) {
const statement = this.database.prepare(`
UPDATE outbox SET refused_code = ?, refused_at = ?
WHERE seq = ? AND acked_at IS NULL AND refused_code IS NULL
`);
return this.transaction(() => {
let changed = 0;
for (const refusal of refusals) changed += Number(statement.run(refusal.code, at, refusal.seq).changes);
return changed;
});
}
/**
* Operator revive: put refused rows back in the pending queue with a fresh
* attempt budget. Used after the hub-side state is corrected — the Runtime
* must not decide on its own that a refusal has become retryable.
*/
retryRefusedOutbox() {
return Number(this.database.prepare(`
UPDATE outbox SET refused_code = NULL, refused_at = NULL, attempted_at = NULL, attempt_count = 0
WHERE acked_at IS NULL AND refused_code IS NOT NULL
`).run().changes);
}
/**
* The outbox as one read model: what is still retryable, what the hub holds,
* and what the hub refused with which codes. This is what makes a stalled
* sync answerable without opening SQLite.
*/
outboxStatus() {
const counts = this.database.prepare(`
SELECT
COALESCE(SUM(acked_at IS NULL AND refused_code IS NULL), 0) AS pending,
COALESCE(SUM(acked_at IS NOT NULL), 0) AS acked,
COALESCE(SUM(acked_at IS NULL AND refused_code IS NOT NULL), 0) AS refused,
MAX(attempted_at) AS last_attempt_at
FROM outbox
`).get();
const refusals = this.database.prepare(`
SELECT refused_code AS code, COUNT(*) AS count
FROM outbox WHERE acked_at IS NULL AND refused_code IS NOT NULL
GROUP BY refused_code ORDER BY count DESC, code ASC
`).all();
const oldest = this.database.prepare(`
SELECT seq FROM outbox WHERE acked_at IS NULL AND refused_code IS NULL ORDER BY seq ASC LIMIT 1
`).get();
return {
pending: counts.pending,
acked: counts.acked,
refused: counts.refused,
...counts.last_attempt_at !== null ? { lastAttemptAt: counts.last_attempt_at } : {},
...oldest ? { oldestPendingSeq: oldest.seq } : {},
// Mapped, not spread: node:sqlite rows are null-prototype objects, and this
// read model is handed straight to the CLI and the supervisor's JSON answer.
refusals: refusals.map((refusal) => ({ code: refusal.code, count: refusal.count }))
};
}
events(runId, afterSequence = 0, limit = 200) {
const rows = this.database.prepare(`
SELECT project_id, run_id, sequence, event_id, event_type, command_id, occurred_at, recorded_at, monotonic_ns, config_revision, memory_revision, executor_policy_revision, tool_policy_revision, payload, schema, home_runtime_id
FROM events WHERE run_id = ? AND sequence > ? ORDER BY sequence ASC LIMIT ?
`).all(runId, afterSequence, limit);
return rows.map((row) => ({
schema: row.schema,
eventId: row.event_id,
eventType: row.event_type,
projectId: row.project_id,
runId: row.run_id,
homeRuntimeId: row.home_runtime_id,
sequence: row.sequence,
...row.command_id !== null ? { commandId: row.command_id } : {},
occurredAt: row.occurred_at,
recordedAt: row.recorded_at,
monotonicNs: row.monotonic_ns,
configRevision: row.config_revision,
memoryRevision: row.memory_revision,
executorPolicyRevision: row.executor_policy_revision,
toolPolicyRevision: row.tool_policy_revision,
payload: JSON.parse(row.payload)
}));
}
insertRunPlan(row) {
this.database.prepare("INSERT INTO run_plans (run_id, run_plan_hash, envelope, pinned_sequence) VALUES (?, ?, ?, ?)").run(row.runId, row.runPlanHash, row.envelope, row.pinnedSequence);
}
runPlan(runId) {
const row = this.database.prepare("SELECT run_id, run_plan_hash, envelope, pinned_sequence FROM run_plans WHERE run_id = ?").get(runId);
return row ? { runId: row.run_id, runPlanHash: row.run_plan_hash, envelope: row.envelope, pinnedSequence: row.pinned_sequence } : void 0;
}
runState(runId) {
const row = this.database.prepare("SELECT run_id, last_sequence, state FROM run_state WHERE run_id = ?").get(runId);
return row ? { runId: row.run_id, lastSequence: row.last_sequence, state: row.state } : void 0;
}
upsertRunState(row) {
this.database.prepare(`
INSERT INTO run_state (run_id, last_sequence, state) VALUES (?, ?, ?)
ON CONFLICT(run_id) DO UPDATE SET last_sequence = excluded.last_sequence, state = excluded.state
`).run(row.runId, row.lastSequence, row.state);
}
insertDriveReceipt(receipt) {
validateDriveReceipt(receipt, "drive-receipt");
const canonical = kxmCanonicalJson(receipt);
if (Buffer.byteLength(canonical, "utf8") > DRIVE_RECEIPT_MAX_BYTES) {
throw runtimeError("drive_receipt_invalid", receipt.driveId, `drive receipt exceeds ${DRIVE_RECEIPT_MAX_BYTES} bytes`);
}
const result = this.database.prepare(`
INSERT INTO drive_receipts (drive_id, run_id, project_id, opened_sequence, last_sequence, closed_at, schema, receipt)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(drive_id) DO NOTHING
`).run(
receipt.driveId,
receipt.runId,
receipt.projectId,
receipt.openedSequence,
receipt.lastSequence,
receipt.closedAt,
receipt.schema,
canonical
);
return { inserted: Number(result.changes) === 1 };
}
driveReceipt(driveId) {
const row = this.database.prepare("SELECT receipt FROM drive_receipts WHERE drive_id = ?").get(driveId);
return row ? parseDriveReceipt(row.receipt) : void 0;
}
driveReceiptsForRun(runId, limit = 20) {
const rows = this.database.prepare(`
SELECT drive_id, receipt FROM drive_receipts WHERE run_id = ? ORDER BY closed_at DESC, drive_id DESC LIMIT ?
`).all(runId, limit);
return rows.map((row) => {
try {
return parseDriveReceipt(row.receipt);
} catch {
return { driveId: row.drive_id, divergence: "receipt unreadable" };
}
});
}
/** Insert a coordinator unless the (project, role, channel) slot is taken. */
insertCoordinatorIfAbsent(row) {
const result = this.database.prepare(`
INSERT OR IGNORE INTO coordinators
(coordinator_id, project_id, role, channel, ceiling_hash, config_revision, bound_at, schema, record)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
row.coordinatorId,
row.projectId,
row.role,
row.channel,
row.ceilingHash,
row.configRevision,
row.boundAt,
"kxm.coordinator.v1",
row.record
);
return Number(result.changes) === 1;
}
coordinatorById(coordinatorId) {
const row = this.database.prepare("SELECT * FROM coordinators WHERE coordinator_id = ?").get(coordinatorId);
return row ? coordinatorFromRow(row) : void 0;
}
coordinatorInSlot(projectId, role, channel) {
const row = this.database.prepare(`
SELECT * FROM coordinators WHERE project_id = ? AND role = ? AND channel = ?
`).get(projectId, role, channel);
return row ? coordinatorFromRow(row) : void 0;
}
/**
* Replace the coordinator holding a (project, role, channel) slot, guarded by
* the identity that is currently there. A rebind therefore cannot clobber a
* record that changed underneath it, and cannot leave two live identities for
* one slot.
*/
replaceCoordinatorInSlot(expectedCoordinatorId, row) {
const result = this.database.prepare(`
UPDATE coordinators
SET coordinator_id = ?, ceiling_hash = ?, config_revision = ?, bound_at = ?, schema = ?, record = ?
WHERE project_id = ? AND role = ? AND channel = ? AND coordinator_id = ?
`).run(
row.coordinatorId,
row.ceilingHash,
row.configRevision,
row.boundAt,
"kxm.coordinator.v1",
row.record,
row.projectId,
row.role,
row.channel,
expectedCoordinatorId
);
return Number(result.changes) === 1;
}
/** Insert an intake message unless its idempotency slot is taken. */
insertIntakeMessageIfAbsent(row) {
const result = this.database.prepare(`
INSERT OR IGNORE INTO intake_messages
(message_id, project_id, coordinator_id, idempotency_key, content_hash, received_at, dispatch_state, schema, record)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
row.messageId,
row.projectId,
row.coordinatorId,
row.idempotencyKey,
row.contentHash,
row.receivedAt,
row.dispatchState,
"kxm.intake-message.v1",
row.record
);
return Number(result.changes) === 1;
}
intakeMessage(messageId) {
const row = this.database.prepare("SELECT * FROM intake_messages WHERE message_id = ?").get(messageId);
return row ? intakeFromRow(row) : void 0;
}
intakeBySlot(projectId, coordinatorId, idempotencyKey) {
const row = this.database.prepare(`
SELECT * FROM intake_messages WHERE project_id = ? AND coordinator_id = ? AND idempotency_key = ?
`).get(projectId, coordinatorId, idempotencyKey);
return row ? intakeFromRow(row) : void 0;
}
/**
* Intake rows in the given dispatch states, in arrival order (replay-safe).
*
* `rowid` gives same-store arrival order, which is what queue priority needs
* here. It is **not** a durable sequence: this repository backs stores up with
* `VACUUM INTO`, and a vacuum may renumber implicit rowids. An explicit
* immutable arrival sequence is tracked in the plan's schema-v6 follow-ups.
*/
intakeInStates(projectId, states, limit = 100) {
if (states.length === 0) return [];
const placeholders = states.map(() => "?").join(", ");
const rows = this.database.prepare(`
SELECT * FROM intake_messages
WHERE project_id = ? AND dispatch_state IN (${placeholders})
ORDER BY rowid ASC
LIMIT ?
`).all(projectId, ...states, limit);
return rows.map(intakeFromRow);
}
/** Rewrite one intake row's dispatch state and record. Returns false when it raced away. */
updateIntakeDispatch(messageId, expectState, next) {
const result = this.database.prepare(`
UPDATE intake_messages SET dispatch_state = ?, record = ?, schema = ?
WHERE message_id = ? AND dispatch_state = ?
`).run(next.state, next.record, "kxm.intake-message.v1", messageId, expectState);
return Number(result.changes) === 1;
}
projectControl(projectId) {
const row = this.database.prepare("SELECT * FROM project_controls WHERE project_id = ?").get(projectId);
return row ? controlFromRow(row) : void 0;
}
putProjectControl(row) {
this.database.prepare(`
INSERT INTO project_controls (project_id, paused, reason, updated_at, actor, schema, record)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(project_id) DO UPDATE SET
paused = excluded.paused,
reason = excluded.reason,
updated_at = excluded.updated_at,
actor = excluded.actor,
schema = excluded.schema,
record = excluded.record
`).run(
row.projectId,
row.paused ? 1 : 0,
row.reason ?? null,
row.updatedAt,
row.actor,
"kxm.project-control.v1",
row.record
);
}
insertCapability(row) {
this.database.prepare(`
INSERT INTO attempt_capabilities (attempt_id, run_id, assignment_id, step_id, step_attempt, producer_id, capability_hash, state)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(row.attemptId, row.runId, row.assignmentId, row.stepId, row.stepAttempt, row.producerId, row.capabilityHash, row.state);
}
capabilityByHash(capabilityHash) {
return capabilityFromRow(this.database.prepare(`
SELECT attempt_id, run_id, assignment_id, step_id, step_attempt, producer_id, capability_hash, state
FROM attempt_capabilities WHERE capability_hash = ?
`).get(capabilityHash));
}
capabilityByAttempt(attemptId) {
return capabilityFromRow(this.database.prepare(`
SELECT attempt_id, run_id, assignment_id, step_id, step_attempt, producer_id, capability_hash, state
FROM attempt_capabilities WHERE attempt_id = ?
`).get(attemptId));
}
settleCapability(attemptId, state) {
const updated = this.database.prepare("UPDATE attempt_capabilities SET state = ? WHERE attempt_id = ?").run(state, attemptId);
if (Number(updated.changes) !== 1) {
throw runtimeError("capability_unknown", attemptId, "attempt capability does not exist");
}
}
insertGateAttempt(row) {
assertGateAttemptRow(row);
this.assertEventType(row.runId, row.intentEventId, ["effect.intent_recorded"]);
const capability = this.capabilityByAttempt(row.attemptId);
if (!capability || capability.runId !== row.runId || capability.assignmentId !== row.assignmentId || capability.stepId !== row.stepId || capability.stepAttempt !== row.stepAttempt) {
throw gateRowInvalid(row.attemptId, "gate attempt identity does not match attempt_capabilities");
}
this.database.prepare(`
INSERT INTO gate_attempts (
attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id, effect_id,
gate_id, gate_kind, expect, gate_definition_hash, registry_hash, run_plan_hash, control_project_key,
producer_id, intent_event_id, content_hash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
row.attemptId,
row.runId,
row.projectId,
row.homeRuntimeId,
row.stepId,
row.stepAttempt,
row.assignmentId,
row.effectId,
row.gateId,
row.gateKind,
row.expect,
row.gateDefinitionHash,
row.registryHash,
row.runPlanHash,
row.controlProjectKey,
row.producerId,
row.intentEventId,
row.contentHash
);
}
insertGateObservation(row) {
assertGateObservationRow(row);
this.assertEventType(row.runId, row.recordedEventId, ["effect.observed", "effect.blocked_uncertain"]);
const attempt = this.gateAttempt(row.attemptId);
if (!attempt) throw gateRowInvalid(row.attemptId, "gate observation has no matching gate attempt");
assertSharedIdentity(row, attempt, row.observationId);
assertClosedGateObservation(attempt.gateKind, row, row.observationId);
this.database.prepare(`
INSERT INTO gate_observations (
observation_id, attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id, effect_id,
completeness, spawned, pid, exit_code, signal, exit_observed, close_observed, stop_cause, signals_attempted,
error_class, stdout_sha256, stdout_bytes, stdout_complete, stderr_sha256, stderr_bytes, stderr_complete,
checked_count, failed_count, elapsed_ms, started_at, finished_at, recorded_event_id, content_hash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
row.observationId,
row.attemptId,
row.runId,
row.projectId,
row.homeRuntimeId,
row.stepId,
row.stepAttempt,
row.assignmentId,
row.effectId,
row.completeness,
row.spawned,
row.pid,
row.exitCode,
row.signal,
row.exitObserved,
row.closeObserved,
row.stopCause,
row.signalsAttempted,
row.errorClass,
row.stdoutSha256,
row.stdoutBytes,
row.stdoutComplete,
row.stderrSha256,
row.stderrBytes,
row.stderrComplete,
row.checkedCount,
row.failedCount,
row.elapsedMs,
row.startedAt,
row.finishedAt,
row.recordedEventId,
row.contentHash
);
}
insertGateEvidence(row) {
assertGateEvidenceRow(row);
this.assertEventType(row.runId, row.settledEventId, ["effect.settled"]);
const attempt = this.gateAttempt(row.attemptId);
if (!attempt) throw gateRowInvalid(row.attemptId, "gate evidence has no matching gate attempt");
assertSharedIdentity(row, attempt, row.evidenceId);
const observation = this.gateObservationForAttempt(row.attemptId);
if (!observation || observation.observationId !== row.observationId) {
throw gateRowInvalid(row.evidenceId, "gate evidence observation_id does not match the attempt observation");
}
this.database.prepare(`
INSERT INTO gate_evidence (
evidence_id, attempt_id, observation_id, run_id, project_id, home_runtime_id, step_id, step_attempt,
assignment_id, effect_id, evidence_key, kind, expect, outcome, settled_event_id, content_hash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
row.evidenceId,
row.attemptId,
row.observationId,
row.runId,
row.projectId,
row.homeRuntimeId,
row.stepId,
row.stepAttempt,
row.assignmentId,
row.effectId,
row.evidenceKey,
row.kind,
row.expect,
row.outcome,
row.settledEventId,
row.contentHash
);
}
gateAttempt(attemptId) {
const row = this.database.prepare(`
SELECT attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id, effect_id,
gate_id, gate_kind, expect, gate_definition_hash, registry_hash, run_plan_hash, control_project_key,
producer_id, intent_event_id, content_hash
FROM gate_attempts WHERE attempt_id = ?
`).get(attemptId);
return row ? gateAttemptFromSql(row) : void 0;
}
gateAttemptsForRun(runId) {
const rows = this.database.prepare(`
SELECT attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id, effect_id,
gate_id, gate_kind, expect, gate_definition_hash, registry_hash, run_plan_hash, control_project_key,
producer_id, intent_event_id, content_hash
FROM gate_attempts WHERE run_id = ? ORDER BY step_attempt ASC, attempt_id ASC
`).all(runId);
return rows.map(gateAttemptFromSql);
}
gateAttemptsForProject(projectId) {
const rows = this.database.prepare(`
SELECT attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id, effect_id,
gate_id, gate_kind, expect, gate_definition_hash, registry_hash, run_plan_hash, control_project_key,
producer_id, intent_event_id, content_hash
FROM gate_attempts WHERE project_id = ? ORDER BY run_id ASC, step_attempt ASC, attempt_id ASC
`).all(projectId);
return rows.map(gateAttemptFromSql);
}
issuedOrRevokedCapabilities() {
const rows = this.database.prepare(`
SELECT attempt_id, run_id, assignment_id, step_id, step_attempt, producer_id, capability_hash, state
FROM attempt_capabilities
WHERE state IN ('issued','revoked')
ORDER BY run_id ASC, step_attempt ASC, attempt_id ASC
`).all();
const mapped = [];
for (const row of rows) {
const capability = capabilityFromRow(row);
if (!capability) {
throw runtimeError("gate_recovery_corrupt", "attempt_capabilities", "issued or revoked capability row could not be read");
}
mapped.push(capability);
}
return mapped;
}
gateObservationForAttempt(attemptId) {
const row = this.database.prepare(`
SELECT observation_id, attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id,
effect_id, completeness, spawned, pid, exit_code, signal, exit_observed, close_observed, stop_cause,
signals_attempted, error_class, stdout_sha256, stdout_bytes, stdout_complete, stderr_sha256, stderr_bytes,
stderr_complete, checked_count, failed_count, elapsed_ms, started_at, finished_at, recorded_event_id, content_hash
FROM gate_observations WHERE attempt_id = ?
`).get(attemptId);
return row ? gateObservationFromSql(row) : void 0;
}
gateObservationsForRun(runId) {
const rows = this.database.prepare(`
SELECT observation_id, attempt_id, run_id, project_id, home_runtime_id, step_id, step_attempt, assignment_id,
effect_id, completeness, spawned, pid, exit_code, signal, exit_observed, close_observed, stop_cause,
signals_attempted, error_class, stdout_sha256, stdout_bytes, stdout_complete, stderr_sha256, stderr_bytes,
stderr_complete, checked_count, failed_count, elapsed_ms, started_at, finished_at, recorded_event_id, content_hash
FROM gate_observations WHERE run_id = ? ORDER BY step_attempt ASC, observation_id ASC
`).all(runId);
return rows.map(gateObservationFromSql);
}
gateEvidenceForRun(runId) {
const rows = this.database.prepare(`
SELECT evidence_id, attempt_id, observation_id, run_id, project_id, home_runtime_id, step_id, step_attempt,
assignment_id, effect_id, evidence_key, kind, expect, outcome, settled_event_id, content_hash
FROM gate_evidence WHERE run_id = ? ORDER BY step_attempt ASC, evidence_id ASC
`).all(runId);
return rows.map(gateEvidenceFromSql);
}
gateEvidenceForAttempt(attemptId) {
const row = this.database.prepare(`
SELECT evidence_id, attempt_id, observation_id, run_id, project_id, home_runtime_id, step_id, step_attempt,
assignment_id, effect_id, evidence_key, kind, expect, outcome, settled_event_id, content_hash
FROM gate_evidence WHERE attempt_id = ?
`).get(attemptId);
return row ? gateEvidenceFromSql(row) : void 0;
}
gateRowCounts(runId) {
const attempts = this.database.prepare("SELECT COUNT(*) AS n FROM gate_attempts WHERE run_id = ?").get(runId);
const observations = this.database.prepare("SELECT COUNT(*) AS n FROM gate_observations WHERE run_id = ?").get(runId);
const evidence = this.database.prepare("SELECT COUNT(*) AS n FROM gate_evidence WHERE run_id = ?").get(runId);
return { attempts: Number(attempts.n), observations: Number(observations.n), evidence: Number(evidence.n) };
}
assertEventType(runId, eventId, allowed) {
const row = this.database.prepare("SELECT run_id, event_type FROM events WHERE event_id = ?").get(eventId);
if (!row || row.run_id !== runId || !allowed.includes(row.event_type)) {
throw gateRowInvalid(eventId, `referenced event is not ${allowed.join("|")} for this run`);
}
}
};
function coordinatorFromRow(row) {
const parsed = JSON.parse(row.record);
if (row.schema !== "kxm.coordinator.v1") {
throw runtimeError("coordinator_record_divergent", row.coordinator_id, `unexpected coordinator schema ${row.schema}`);
}
validateCoordinator(parsed, row.coordinator_id);
if (parsed.coordinatorId !== row.coordinator_id || parsed.projectId !== row.project_id || parsed.role !== row.role || parsed.channel !== row.channel || parsed.ceilingHash !== row.ceiling_hash || parsed.configRevision !== row.config_revision || parsed.boundAt !== row.bound_at) {
throw runtimeError("coordinator_record_divergent", row.coordinator_id, "coordinator columns do not match the persisted record");
}
return {
coordinatorId: row.coordinator_id,
projectId: row.project_id,
role: row.role,
channel: row.channel,
ceilingHash: row.ceiling_hash,
configRevision: row.config_revision,
boundAt: row.bound_at,
record: row.record
};
}
function intakeFromRow(row) {
const parsed = JSON.parse(row.record);
if (row.schema !== "kxm.intake-message.v1") {
throw runtimeError("intake_record_divergent", row.message_id, `unexpected intake schema ${row.schema}`);
}
validateIntakeMessage(parsed, row.message_id);
if (parsed.messageId !== row.message_id || parsed.projectId !== row.project_id || parsed.coordinatorId !== row.coordinator_id || parsed.idempotencyKey !== row.idempotency_key || parsed.contentHash !== row.content_hash || parsed.receivedAt !== row.received_at || parsed.dispatch?.state !== row.dispatch_state) {
throw runtimeError("intake_record_divergent", row.message_id, "intake columns do not match the persisted record");
}
return {
messageId: row.message_id,
projectId: row.project_id,
coordinatorId: row.coordinator_id,
idempotencyKey: row.idempotency_key,
contentHash: row.content_hash,
receivedAt: row.received_at,
dispatchState: row.dispatch_state,
record: row.record
};
}
function controlFromRow(row) {
const paused = row.paused === 1;
const expected = kxmCanonicalJson({
schema: "kxm.project-control.v1",
projectId: row.project_id,
paused,
...row.reason !== null ? { reason: row.reason } : {},
updatedAt: row.updated_at,
actor: row.actor
});
if (row.record !== expected) {
throw runtimeError("project_control_divergent", row.project_id, "project control record does not match its columns");
}
return {
projectId: row.project_id,
paused,
...row.reason !== null ? { reason: row.reason } : {},
updatedAt: row.updated_at,
actor: row.actor,
record: row.record
};
}
function parseDriveReceipt(raw) {
const parsed = JSON.parse(raw);
validateDriveReceipt(parsed, "drive-receipt");
return parsed;
}
function outboxFromRow(row) {
return {
seq: row.seq,
runId: row.run_id,
sequence: row.sequence,
syncEvent: row.sync_event,
attemptCount: row.attempt_count,
...row.attempted_at !== null ? { attemptedAt: row.attempted_at } : {},
...row.acked_at !== null ? { ackedAt: row.acked_at } : {},
...row.refused_code !== null ? { refusedCode: row.refused_code } : {},
...row.refused_at !== null ? { refusedAt: row.refused_at } : {}
};
}
function runFromRow(row) {
if (typeof row.memory_revision !== "string" || row.memory_revision.length === 0) {
throw runtimeError("runtime_schema_shape_invalid", row.run_id, "memory_revision is required");
}
return {
runId: row.run_id,
projectId: row.project_id,
homeRuntimeId: row.home_runtime_id,
workflowId: row.workflow_id,
promptSha256: row.prompt_sha256,
status: row.status,
configRevision: row.config_revision,
memoryRevision: row.memory_revision,
executorPolicyRevision: row.executor_policy_revision,
toolPolicyRevision: row.tool_policy_revision,
createdAt: row.created_at,
updatedAt: row.updated_at
};
}
function newKxmRunId() {
return `run_${randomUUID().replaceAll("-", "")}`;
}
function newKxmEventId() {
return `evt_${randomUUID().replaceAll("-", "")}`;
}
function newKxmCommandId() {
return `cmd_${randomUUID().replaceAll("-", "")}`;
}
function newKxmAssignmentId() {
return `asg_${randomUUID().replaceAll("-", "")}`;
}
function newKxmAttemptId() {
return `att_${randomUUID().replaceAll("-", "")}`;
}
function newKxmEffectId() {
return `eff_${randomUUID().replaceAll("-", "")}`;
}
function newKxmObservationId() {
return `obs_${randomUUID().replaceAll("-", "")}`;
}
function newKxmEvidenceId() {
return `gev_${randomUUID().replaceAll("-", "")}`;
}
var SHA2562 = /^sha256:[a-f0-9]{64}$/;
var OPAQUE = /^[a-z][a-z0-9]{1,15}_[A-Za-z0-9][A-Za-z0-9_-]{5,127}$/;
var FORBIDDEN_TEXT_KEYS = /* @__PURE__ */ new Set(["stdout", "stderr", "error", "errorText", "stdoutText", "stderrText", "errorMessage", "message"]);
var GATE_ATTEMPT_KEYS = [
"attemptId",
"runId",
"projectId",
"homeRuntimeId",
"stepId",
"stepAttempt",
"assignmentId",
"effectId",
"gateId",
"gateKind",
"expect",
"gateDefinitionHash",
"registryHash",
"runPlanHash",
"controlProjectKey",
"producerId",
"intentEventId",
"contentHash"
];
var GATE_OBSERVATION_KEYS = [
"observationId",
"attemptId",
"runId",
"projectId",
"homeRuntimeId",
"stepId",
"stepAttempt",
"assignmentId",
"effectId",
"completeness",
"spawned",
"pid",
"exitCode",
"signal",
"exitObserved",
"closeObserved",
"stopCause",
"signalsAttempted",
"errorClass",
"stdoutSha256",
"stdoutBytes",
"stdoutComplete",
"stderrSha256",
"stderrBytes",
"stderrComplete",
"checkedCount",
"failedCount",
"elapsedMs",
"startedAt",
"finishedAt",
"recordedEventId",
"contentHash"
];
var GATE_EVIDENCE_KEYS = [
"evidenceId",
"attemptId",
"observationId",
"runId",
"projectId",
"homeRuntimeId",
"stepId",
"stepAttempt",
"assignmentId",
"effectId",
"evidenceKey",
"kind",
"expect",
"outcome",
"settledEventId",
"contentHash"
];
function gateRowContentHash(table, row) {
const copy = { ...row };
delete copy.contentHash;
void table;
return `sha256:${createHash7("sha256").update(kxmCanonicalJson(copy), "utf8").digest("hex")}`;
}
function assertClosedGateObservation(kind, row, id = "observation") {
if (row.completeness === "incomplete") return;
if (row.completeness === "no-start") {
const legitimateStartFailure = (row.errorClass === "validation" || row.errorClass === "spawn-error") && row.stopCause === "none";
const requestedStop = row.stopCause === "cancel" && row.errorClass === null;
if (row.spawned !== 0 || row.pid !== null || row.exitCode !== null || row.signal !== null || row.exitObserved !== 0 || row.closeObserved !== 0 || row.signalsAttempted !== "none" || row.stdoutSha256 !== null || row.stdoutBytes !== null || row.stdoutComplete !== null || row.stderrSha256 !== null || row.stderrBytes !== null || row.stderrComplete !== null || row.checkedCount !== null || row.failedCount !== null || !legitimateStartFailure && !requestedStop) {
throw gateRowInvalid(id, "no-start observation forbids PID/exit/close/stream/check facts and requires a legitimate no-start cause");
}
return;
}
if (kind === "command") {
if (row.spawned !== 1 || typeof row.pid !== "number" || typeof row.exitCode !== "number" || row.signal !== null || row.exitObserved !== 1 || row.closeObserved !== 1 || row.stopCause !== "none" || row.signalsAttempted !== "none" || row.stdoutComplete !== 1 || row.stderrComplete !== 1 || typeof row.stdoutSha256 !== "string" || typeof row.stderrSha256 !== "string" || typeof row.stdoutBytes !== "number" || typeof row.stderrBytes !== "number" || row.checkedCount !== null || row.failedCount !== null) {
throw gateRowInvalid(id, "complete command observation requires spawn, numeric exit, no signal, exit/close, complete streams, and stopCause none");
}
return;
}
if (row.spawned !== 0 || row.pid !== null || row.exitCode !== null || row.signal !== null || row.exitObserved !== 0 || row.closeObserved !== 0 || row.stopCause !== "none" || row.signalsAttempted !== "none" || row.stdoutSha256 !== null || row.stdoutBytes !== null || row.stdoutComplete !== null || row.stderrSha256 !== null || row.stderrBytes !== null || row.stderrComplete !== null || typeof row.checkedCount !== "number" || typeof row.failedCount !== "number" || row.checkedCount < 0 || row.failedCount < 0 || row.failedCount > row.checkedCount) {
throw gateRowInvalid(id, "complete artifacts observation requires consistent counts and no command facts");
}
}
function computeGateEvidenceOutcome(kind, expect, observation) {
assertClosedGateObservation(kind, observation);
if (observation.completeness !== "complete") {
throw gateRowInvalid("observation", "evaluated settlement requires a complete observation");
}
if (kind === "artifacts-exist") {
if (expect === "fail") throw gateRowInvalid("artifacts-exist", "artifacts-exist cannot expect fail");
return observation.failedCount === 0 ? "passed" : "implementation-failure";
}
if (expect === "pass") return observation.exitCode === 0 ? "passed" : "implementation-failure";
return observation.exitCode === 0 ? "repro-missing" : "passed";
}
function gateRowInvalid(file, message) {
return runtimeError("gate_row_invalid", file, message);
}
function assertExactRowKeys(row, keys, id) {
const actual = Object.keys(row);
if (actual.length !== keys.length || keys.some((key) => !Object.prototype.hasOwnProperty.call(row, key))) {
throw gateRowInvalid(id, "gate row does not have the exact key set");
}
for (const key of actual) {
if (FORBIDDEN_TEXT_KEYS.has(key)) throw gateRowInvalid(id, "gate row must not carry raw stdout/stderr/error text");
}
}
function assertId(value, prefix, id, label) {
if (typeof value !== "string" || !value.startsWith(prefix) || !OPAQUE.test(value)) {
throw gateRowInvalid(id, `${label} is not a valid ${prefix} opaque id`);
}
}
function assertSha(value, id, label) {
if (typeof value !== "string" || !SHA2562.test(value)) throw gateRowInvalid(id, `${label} is not a sha256 hash`);
}
function assertFlag(value, id, label) {
if (value !== 0 && value !== 1) throw gateRowInvalid(id, `${label} must be 0 or 1`);
}
function assertNullInt(value, id, label) {
if (value !== null && (typeof value !== "number" || !Number.isInteger(value))) {
throw gateRowInvalid(id, `${label} must be an integer or null`);
}
}
function assertGateAttemptRow(row) {
assertExactRowKeys(row, GATE_ATTEMPT_KEYS, row.attemptId);
assertId(row.attemptId, "att_", row.attemptId, "attemptId");
assertId(row.effectId, "eff_", row.attemptId, "effectId");
assertId(row.intentEventId, "evt_", row.attemptId, "intentEventId");
assertSha(row.gateDefinitionHash, row.attemptId, "gateDefinitionHash");
assertSha(row.registryHash, row.attemptId, "registryHash");
assertSha(row.runPlanHash, row.attemptId, "runPlanHash");
if (row.producerId !== "kxm-gate") throw gateRowInvalid(row.attemptId, "producerId must be kxm-gate");
if (row.gateKind !== "command" && row.gateKind !== "artifacts-exist") {
throw gateRowInvalid(row.attemptId, "gateKind is invalid");
}
if (row.expect !== "pass" && row.expect !== "fail") throw gateRowInvalid(row.attemptId, "expect is invalid");
if (row.gateKind === "artifacts-exist" && row.expect === "fail") {
throw gateRowInvalid(row.attemptId, "artifacts-exist cannot expect fail");
}
if (typeof row.controlProjectKey !== "string" || row.controlProjectKey.length === 0) {
throw gateRowInvalid(row.attemptId, "controlProjectKey is required");
}
if (gateRowContentHash("gate_attempts", row) !== row.contentHash) {
throw gateRowInvalid(row.attemptId, "contentHash does not match the canonical row");
}
}
function assertGateObservationRow(row) {
assertExactRowKeys(row, GATE_OBSERVATION_KEYS, row.observationId);
assertId(row.observationId, "obs_", row.observationId, "observationId");
assertId(row.attemptId, "att_", row.observationId, "attemptId");
assertId(row.effectId, "eff_", row.observationId, "effectId");
assertId(row.recordedEventId, "evt_", row.observationId, "recordedEventId");
if (!["complete", "incomplete", "no-start"].includes(row.completeness)) {
throw gateRowInvalid(row.observationId, "completeness is invalid");
}
assertFlag(row.spawned, row.observationId, "spawned");
assertFlag(row.exitObserved, row.observationId, "exitObserved");
assertFlag(row.closeObserved, row.observationId, "closeObserved");
assertNullInt(row.pid, row.observationId, "pid");
assertNullInt(row.exitCode, row.observationId, "exitCode");
assertNullInt(row.stdoutBytes, row.observationId, "stdoutBytes");
assertNullInt(row.stderrBytes, row.observationId, "stderrBytes");
assertNullInt(row.checkedCount, row.observationId, "checkedCount");
assertNullInt(row.failedCount, row.observationId, "failedCount");
if (typeof row.elapsedMs !== "number" || !Number.isInteger(row.elapsedMs) || row.elapsedMs < 0) {
throw gateRowInvalid(row.observationId, "elapsedMs is invalid");
}
if (row.stdoutSha256 !== null) assertSha(row.stdoutSha256, row.observationId, "stdoutSha256");
if (row.stderrSha256 !== null) assertSha(row.stderrSha256, row.observationId, "stderrSha256");
if (row.stdoutComplete !== null && row.stdoutComplete !== 0 && row.stdoutComplete !== 1) {
throw gateRowInvalid(row.observationId, "stdoutComplete must be 0, 1, or null");
}
if (row.stderrComplete !== null && row.stderrComplete !== 0 && row.stderrComplete !== 1) {
throw gateRowInvalid(row.observationId, "stderrComplete must be 0, 1, or null");
}
if (gateRowContentHash("gate_observations", row) !== row.contentHash) {
throw gateRowInvalid(row.observationId, "contentHash does not match the canonical row");
}
}
function assertGateEvidenceRow(row) {
assertExactRowKeys(row, GATE_EVIDENCE_KEYS, row.evidenceId);
assertId(row.evidenceId, "gev_", row.evidenceId, "evidenceId");
assertId(row.attemptId, "att_", row.evidenceId, "attemptId");
assertId(row.observationId, "obs_", row.evidenceId, "observationId");
assertId(row.effectId, "eff_", row.evidenceId, "effectId");
assertId(row.settledEventId, "evt_", row.evidenceId, "settledEventId");
if (row.kind !== "gate") throw gateRowInvalid(row.evidenceId, "kind must be gate");
if (!["passed", "implementation-failure", "repro-missing"].includes(row.outcome)) {
throw gateRowInvalid(row.evidenceId, "outcome is invalid");
}
if (gateRowContentHash("gate_evidence", row) !== row.contentHash) {
throw gateRowInvalid(row.evidenceId, "contentHash does not match the canonical row");
}
}
function assertSharedIdentity(row, attempt, id) {
if (row.runId !== attempt.runId || row.projectId !== attempt.projectId || row.homeRuntimeId !== attempt.homeRuntimeId || row.stepId !== attempt.stepId || row.stepAttempt !== attempt.stepAttempt || row.assignmentId !== attempt.assignmentId || row.effectId !== attempt.effectId) {
throw gateRowInvalid(id, "row identity does not match the gate attempt");
}
}
function gateAttemptFromSql(row) {
return {
attemptId: row.attempt_id,
runId: row.run_id,
projectId: row.project_id,
homeRuntimeId: row.home_runtime_id,
stepId: row.step_id,
stepAttempt: row.step_attempt,
assignmentId: row.assignment_id,
effectId: row.effect_id,
gateId: row.gate_id,
gateKind: row.gate_kind,
expect: row.expect,
gateDefinitionHash: row.gate_definition_hash,
registryHash: row.registry_hash,
runPlanHash: row.run_plan_hash,
controlProjectKey: row.control_project_key,
producerId: row.producer_id,
intentEventId: row.intent_event_id,
contentHash: row.content_hash
};
}
function gateObservationFromSql(row) {
return {
observationId: row.observation_id,
attemptId: row.attempt_id,
runId: row.run_id,
projectId: row.project_id,
homeRuntimeId: row.home_runtime_id,
stepId: row.step_id,
stepAttempt: row.step_attempt,
assignmentId: row.assignment_id,
effectId: row.effect_id,
completeness: row.completeness,
spawned: row.spawned === 1 ? 1 : 0,
pid: row.pid,
exitCode: row.exit_code,
signal: row.signal,
exitObserved: row.exit_observed === 1 ? 1 : 0,
closeObserved: row.close_observed === 1 ? 1 : 0,
stopCause: row.stop_cause,
signalsAttempted: row.signals_attempted,
errorClass: row.error_class,
stdoutSha256: row.stdout_sha256,
stdoutBytes: row.stdout_bytes,
stdoutComplete: row.stdout_complete === null ? null : row.stdout_complete === 1 ? 1 : 0,
stderrSha256: row.stderr_sha256,
stderrBytes: row.stderr_bytes,
stderrComplete: row.stderr_complete === null ? null : row.stderr_complete === 1 ? 1 : 0,
checkedCount: row.checked_count,
failedCount: row.failed_count,
elapsedMs: row.elapsed_ms,
startedAt: row.started_at,
finishedAt: row.finished_at,
recordedEventId: row.recorded_event_id,
contentHash: row.content_hash
};
}
function gateEvidenceFromSql(row) {
return {
evidenceId: row.evidence_id,
attemptId: row.attempt_id,
observationId: row.observation_id,
runId: row.run_id,
projectId: row.project_id,
homeRuntimeId: row.home_runtime_id,
stepId: row.step_id,
stepAttempt: row.step_attempt,
assignmentId: row.assignment_id,
effectId: row.effect_id,
evidenceKey: row.evidence_key,
kind: row.kind,
expect: row.expect,
outcome: row.outcome,
settledEventId: row.settled_event_id,
contentHash: row.content_hash
};
}
function capabilityFromRow(row) {
return row ? {
attemptId: row.attempt_id,
runId: row.run_id,
assignmentId: row.assignment_id,
stepId: row.step_id,
stepAttempt: row.step_attempt,
producerId: row.producer_id,
capabilityHash: row.capability_hash,
state: row.state
} : void 0;
}
// plugins/kxm/src/engine-fold.ts
var KXM_RUN_STATE_SCHEMA = "kxm.run-state.v2";
var FOLD_PANEL_BOUND = 1;
var RUN_STATUSES = /* @__PURE__ */ new Set(["created", "preparing", "running", "waiting", "blocked_uncertain", "cancelling", "cancelled", "completed", "failed"]);
var TERMINAL_RUN = /* @__PURE__ */ new Set(["cancelled", "completed", "failed"]);
var STEP_STATUSES = /* @__PURE__ */ new Set(["pending", "preparing", "running", "passed", "failed", "cancelled"]);
var ASSIGNMENT_STATUSES = /* @__PURE__ */ new Set(["created", "accepted", "dispatched", "executing", "result_recorded", "terminal"]);
var ATTEMPT_STATUSES = /* @__PURE__ */ new Set(["created", "starting", "executing", "settling", "terminal"]);
var RESULT_CLASSES = /* @__PURE__ */ new Set(["outcome", "outcome_unknown", "producer_rejected", "cancelled"]);
var SLICE_BLOCKED_RUN = /* @__PURE__ */ new Set(["waiting"]);
var RUN_EDGES = {
created: /* @__PURE__ */ new Set(["preparing", "cancelled", "failed"]),
preparing: /* @__PURE__ */ new Set(["running", "cancelled", "failed"]),
running: /* @__PURE__ */ new Set(["blocked_uncertain", "cancelling", "cancelled", "completed", "failed"]),
waiting: /* @__PURE__ */ new Set(["running", "blocked_uncertain", "cancelling", "completed", "failed", "cancelled"]),
blocked_uncertain: /* @__PURE__ */ new Set(["running", "cancelling", "failed"]),
cancelling: /* @__PURE__ */ new Set(["cancelled", "failed"]),
cancelled: /* @__PURE__ */ new Set(),
completed: /* @__PURE__ */ new Set(),
failed: /* @__PURE__ */ new Set()
};
var STEP_EDGES = {
pending: /* @__PURE__ */ new Set(["preparing"]),
preparing: /* @__PURE__ */ new Set(["running"]),
running: /* @__PURE__ */ new Set(["passed", "failed", "cancelled"])
};
var ASSIGNMENT_EDGES = {
created: /* @__PURE__ */ new Set(["accepted"]),
accepted: /* @__PURE__ */ new Set(["dispatched"]),
dispatched: /* @__PURE__ */ new Set(["executing"]),
executing: /* @__PURE__ */ new Set(["result_recorded"]),
result_recorded: /* @__PURE__ */ new Set(["terminal"])
};
var ATTEMPT_EDGES = {
created: /* @__PURE__ */ new Set(["starting"]),
starting: /* @__PURE__ */ new Set(["executing"]),
executing: /* @__PURE__ */ new Set(["settling"]),
settling: /* @__PURE__ */ new Set(["terminal"])
};
function effectiveRunDurationBudget(planLimits, projectLimits) {
const workflow = planLimits?.maxRunDurationMs;
const project = projectLimits?.maxRunDurationMs;
if (workflow === void 0 && project === void 0) return void 0;
if (workflow !== void 0 && project !== void 0) {
return { budgetMs: Math.min(workflow, project), source: "both" };
}
if (workflow !== void 0) return { budgetMs: workflow, source: "workflow" };
return { budgetMs: project, source: "project" };
}
function emptyPanel() {
return { order: [], assignments: /* @__PURE__ */ Object.create(null) };
}
function panelAssignmentId(current) {
return current.panel.order[0];
}
function panelAssignment(current, assignmentId) {
const id = assignmentId ?? panelAssignmentId(current);
return id ? current.panel.assignments[id] : void 0;
}
function panelAttemptId(current) {
return panelAssignment(current)?.currentAttemptId;
}
function panelAttempt(current) {
const assignment = panelAssignment(current);
const attemptId = assignment?.currentAttemptId;
return attemptId ? assignment.attempts[attemptId] : void 0;
}
function kxmFoldPanelAttempt(step, attemptId) {
if (!step) return void 0;
for (const assignmentId of step.panel.order) {
const assignment = step.panel.assignments[assignmentId];
const attempt = assignment?.attempts[attemptId];
if (attempt) return { assignmentId, assignment, attempt };
}
return void 0;
}
function findPanelAttempt(panel, attemptId) {
for (const assignmentId of panel.order) {
const assignment = panel.assignments[assignmentId];
const attempt = assignment?.attempts[attemptId];
if (attempt && assignment) return { assignmentId, assignment, attempt };
}
return void 0;
}
function panelAssignmentBound(plan, current) {
const step = plan?.steps[current.stepId];
if (!step) return FOLD_PANEL_BOUND;
if ((step.kind === "agent" || step.kind === "moa") && (step.join.strategy === "all" || step.join.strategy === "all-settled")) {
return step.assignments.maximum;
}
return FOLD_PANEL_BOUND;
}
function panelAssignmentsTerminal(current) {
if (current.panel.order.length === 0) return false;
for (const assignmentId of current.panel.order) {
const assignment = current.panel.assignments[assignmentId];
if (!assignment || assignment.status !== "terminal") return false;
}
return true;
}
function panelIssuedAttemptsTerminal(current) {
for (const assignmentId of current.panel.order) {
const assignment = current.panel.assignments[assignmentId];
if (!assignment) return false;
for (const attempt of Object.values(assignment.attempts)) {
if (attempt.status !== "terminal") return false;
}
}
return true;
}
function panelInFlightCount(panel) {
let count = 0;
for (const assignmentId of panel.order) {
const assignment = panel.assignments[assignmentId];
if (!assignment) continue;
for (const attempt of Object.values(assignment.attempts)) {
if (attempt.status === "starting" || attempt.status === "executing" || attempt.status === "settling") count += 1;
}
}
return count;
}
function panelFrozen(current) {
return current.outcome !== void 0 || current.status === "passed" || current.status === "failed" || current.status === "cancelled";
}
function createdOnlySingletonCancel(state, step, current, status) {
const assignmentId = current.panel.order[0];
const assignment = assignmentId ? current.panel.assignments[assignmentId] : void 0;
return status === "cancelled" && state.cancelRequested && current.panel.order.length === 1 && current.panel.order.length >= step.assignments.minimum && assignment?.status === "created";
}
function authorizedCancelStep(state, step, current, status) {
if (status !== "cancelled" || !state.cancelRequested) return false;
if (createdOnlySingletonCancel(state, step, current, status)) return true;
if (!panelIssuedAttemptsTerminal(current) || !panelAssignmentsTerminal(current)) return false;
const members = [];
for (const assignmentId of current.panel.order) {
const assignment = current.panel.assignments[assignmentId];
if (!assignment) return false;
const issued = Object.values(assignment.attempts);
if (issued.length === 0) return false;
for (const attempt of issued) {
if (attempt.status !== "terminal" || !attempt.resultClass) return false;
}
const currentAttempt = currentAttemptOf(assignment);
if (!currentAttempt?.resultClass) return false;
members.push({ resultClass: currentAttempt.resultClass, outcome: currentAttempt.outcome, producerError: currentAttempt.producerError });
}
if (members.some((member) => member.resultClass === "outcome_unknown" || member.resultClass === "producer_rejected")) {
if (members.every((member) => member.resultClass === "producer_rejected" && member.producerError === "executing_unrecorded")) {
return true;
}
return false;
}
const declared = members.filter((member) => member.resultClass === "outcome");
if (declared.length > 0) {
const outcome = declared[0]?.outcome;
if (typeof outcome !== "string" || declared.some((member) => member.outcome !== outcome)) return false;
}
return members.every((member) => member.resultClass === "outcome" || member.resultClass === "cancelled");
}
function currentAttemptOf(assignment) {
const attemptId = assignment.currentAttemptId;
return attemptId ? assignment.attempts[attemptId] : void 0;
}
function expectedStatusForDeclaredOutcome(step, outcome) {
if (outcome === "passed") return "passed";
if (outcome === "cancelled") return "cancelled";
return "failed";
}
function kxmJoinAll(step, panel) {
if (panel.order.length < step.assignments.minimum) return { tag: "unsatisfied" };
const members = [];
for (const assignmentId of panel.order) {
const assignment = panel.assignments[assignmentId];
if (!assignment || assignment.status !== "terminal") return { tag: "unsatisfied" };
const issued = Object.values(assignment.attempts);
if (issued.length === 0) return { tag: "unsatisfied" };
for (const attempt of issued) {
if (attempt.status !== "terminal" || !attempt.resultClass) return { tag: "unsatisfied" };
}
const current = currentAttemptOf(assignment);
if (!current?.resultClass) return { tag: "unsatisfied" };
members.push({ resultClass: current.resultClass, outcome: current.outcome });
}
if (members.some((member) => member.resultClass === "outcome_unknown" || member.resultClass === "producer_rejected")) {
return { tag: "rejected" };
}
if (members.every((member) => member.resultClass === "cancelled")) return { tag: "cancelled" };
if (step.join.strategy === "all-settled") {
const passedCount = members.filter((m) => m.resultClass === "outcome" && m.outcome === "passed").length;
const minPassed = step.join.minimumPassed ?? step.assignments.minimum;
if (passedCount >= minPassed) {
return { tag: "outcome", outcome: "passed" };
}
const nonPassedGroups = /* @__PURE__ */ new Map();
for (const m of members) {
if (m.resultClass === "outcome" && m.outcome && m.outcome !== "passed") {
nonPassedGroups.set(m.outcome, (nonPassedGroups.get(m.outcome) ?? 0) + 1);
}
}
for (const [outcome, count] of nonPassedGroups) {
if (count >= minPassed) {
return { tag: "outcome", outcome };
}
}
return { tag: "outcome", outcome: "quorum-not-met" };
}
if (members.every((member) => member.resultClass === "outcome")) {
const outcome = members[0]?.outcome;
if (typeof outcome === "string" && members.every((member) => member.outcome === outcome)) {
return { tag: "outcome", outcome };
}
return { tag: "conflict" };
}
return { tag: "conflict" };
}
function putAssignment(current, assignmentId, assignment) {
return {
...current,
panel: {
order: current.panel.order,
assignments: { ...current.panel.assignments, [assignmentId]: assignment }
}
};
}
function kxmFoldPanelAttemptIds(step) {
if (!step) return [];
const ids = [];
for (const assignmentId of step.panel.order) {
const assignment = step.panel.assignments[assignmentId];
if (!assignment) continue;
for (const attemptId of Object.keys(assignment.attempts)) ids.push(attemptId);
}
return ids;
}
function foldKxmRunState(run, plan, events, options = {}) {
if (events.length === 0) {
throw runtimeError("run_events_illegal", run.runId, "run has no events");
}
const state = {
schema: KXM_RUN_STATE_SCHEMA,
runId: run.runId,
status: "created",
stepAttempts: /* @__PURE__ */ Object.create(null),
edgeTransitions: /* @__PURE__ */ Object.create(null),
transitionsUsed: 0,
cancelRequested: false,
terminalEventSeen: false,
awaitingTransition: false
};
for (const [index, event] of events.entries()) {
if (event.sequence !== index + 1) {
throw runtimeError("run_events_illegal", run.runId, `event sequence is not contiguous at ${event.sequence}`);
}
assertEventIdentity(run, event);
if (state.terminalEventSeen) {
throw runtimeError("run_events_illegal", run.runId, "no events are allowed after a terminal run status");
}
if (index === 0 && event.eventType !== "run.created") {
throw runtimeError("run_events_illegal", run.runId, "first event must be run.created");
}
if (state.lastTerminalTransition !== void 0) {
if (event.eventType !== "run.status_changed" || event.payload.status !== state.lastTerminalTransition) {
throw runtimeError("run_events_illegal", run.runId, "terminal transition must be followed by the matching run.status_changed");
}
}
if ((event.eventType.startsWith("step.") || event.eventType.startsWith("assignment.") || event.eventType.startsWith("attempt.") || event.eventType.startsWith("effect.")) && !plan) {
throw runtimeError("run_plan_missing", run.runId, "step events require a pinned run plan");
}
if (state.currentStep?.effectState === "blocked_uncertain") {
const namesFrozen = event.payload.stepId === state.currentStep.stepId || event.payload.attemptId === panelAttemptId(state.currentStep) || event.payload.assignmentId === panelAssignmentId(state.currentStep) || event.payload.effect !== void 0 && typeof event.payload.effect === "object" && event.payload.effect !== null && "id" in event.payload.effect && event.payload.effect.id === state.currentStep.effectId;
const blockedFamily = event.eventType.startsWith("step.") || event.eventType.startsWith("assignment.") || event.eventType.startsWith("attempt.") || event.eventType.startsWith("effect.");
if (blockedFamily && namesFrozen) {
throw runtimeError("run_events_illegal", run.runId, "blocked_uncertain freezes the gate attempt");
}
}
switch (event.eventType) {
case "run.created":
foldRunCreated(state, run, event, index);
break;
case "run.status_changed":
foldRunStatus(state, plan, event);
break;
case "run.cancel_requested":
foldCancelRequested(state, event, plan, options);
break;
case "run.drive_opened":
foldDriveOpened(state, event);
break;
case "step.entered":
foldStepEntered(state, plan, event);
break;
case "step.status_changed":
foldStepStatus(state, plan, event);
break;
case "step.outcome_recorded":
foldOutcome(state, plan, event);
break;
case "step.transitioned":
foldTransitioned(state, plan, event);
break;
case "assignment.created":
foldAssignmentCreated(state, plan, event);
break;
case "assignment.accepted":
foldAssignmentAdvance(state, plan, event, "accepted");
break;
case "assignment.dispatched":
foldAssignmentAdvance(state, plan, event, "dispatched");
break;
case "assignment.executing":
foldAssignmentAdvance(state, plan, event, "executing");
break;
case "assignment.result_recorded":
foldAssignmentAdvance(state, plan, event, "result_recorded");
break;
case "assignment.terminal":
foldAssignmentAdvance(state, plan, event, "terminal");
break;
case "attempt.created":
foldAttemptCreated(state, event);
break;
case "attempt.status_changed":
foldAttemptStatus(state, plan, event);
break;
case "effect.intent_recorded":
foldEffectIntent(state, plan, event);
break;
case "effect.dispatched":
foldEffectDispatched(state, plan, event);
break;
case "effect.observed":
foldEffectObserved(state, plan, event, options);
break;
case "effect.settled":
foldEffectSettled(state, plan, event);
break;
case "effect.blocked_uncertain":
foldEffectUncertain(state, plan, event);
break;
case "routing.attempt.recorded":
case "routing.route_switched":
break;
default:
throw runtimeError("run_events_illegal", run.runId, `event type ${event.eventType} is not legal in this engine slice`);
}
}
if ((state.status === "preparing" || state.status === "running" || state.status === "cancelling") && !plan) {
throw runtimeError("run_plan_missing", run.runId, `status ${state.status} requires a pinned run plan`);
}
return freezeState(state);
}
function assertEventIdentity(run, event) {
if (event.schema !== "kxm.run-event.v1") {
throw runtimeError("run_events_illegal", run.runId, "event schema is not kxm.run-event.v1");
}
if (event.runId !== run.runId || event.projectId !== run.projectId || event.homeRuntimeId !== run.homeRuntimeId) {
throw runtimeError("run_event_owner_mismatch", run.runId, "event identity does not match the run");
}
if (event.configRevision !== run.configRevision || event.memoryRevision !== run.memoryRevision || event.executorPolicyRevision !== run.executorPolicyRevision || event.toolPolicyRevision !== run.toolPolicyRevision) {
throw runtimeError("run_event_owner_mismatch", run.runId, "event revisions do not match the run");
}
}
function foldRunCreated(state, run, event, index) {
if (index !== 0 || event.sequence !== 1) {
throw runtimeError("run_events_illegal", state.runId, "run.created is only legal at sequence 1");
}
if (event.payload.status !== "created") {
throw runtimeError("run_events_illegal", state.runId, "run.created payload status must be created");
}
if (event.payload.workflowId !== run.workflowId) {
throw runtimeError("run_events_illegal", state.runId, "run.created workflowId does not match the run");
}
state.status = "created";
}
function foldRunStatus(state, plan, event) {
const next = event.payload.status;
if (typeof next !== "string" || !RUN_STATUSES.has(next)) {
throw runtimeError("run_events_illegal", state.runId, `run.status_changed has invalid status ${String(next)}`);
}
const status = next;
if (SLICE_BLOCKED_RUN.has(status)) {
throw runtimeError("run_events_illegal", state.runId, `event type ${event.eventType} is not legal in this engine slice`);
}
const allowed = RUN_EDGES[state.status];
if (!allowed?.has(status)) {
throw runtimeError("run_events_illegal", state.runId, `illegal run transition ${state.status} -> ${status}`);
}
if (status === "cancelling") {
if (!state.cancelRequested) {
throw runtimeError("run_events_illegal", state.runId, "cancelling requires run.cancel_requested");
}
}
if (status === "blocked_uncertain") {
if (state.currentStep?.effectState !== "blocked_uncertain") {
throw runtimeError("run_events_illegal", state.runId, "blocked_uncertain requires an uncertain step effect");
}
}
if (status === "running" && state.status === "blocked_uncertain") {
if (state.currentStep) {
state.pendingStepId = state.currentStep.stepId;
state.currentStep = void 0;
}
}
if (status === "preparing") {
const hash = event.payload.runPlanHash;
if (typeof hash !== "string") {
throw runtimeError("run_events_illegal", state.runId, "preparing requires runPlanHash");
}
state.runPlanHash = hash;
}
if ((status === "running" || status === "cancelling") && !plan) {
throw runtimeError("run_plan_missing", state.runId, `status ${status} requires a pinned run plan`);
}
if (status === "running" && state.runningSince === void 0) {
state.runningSince = event.occurredAt;
}
if (TERMINAL_RUN.has(status)) {
assertTerminalRunStatus(state, plan, status, event);
if (typeof event.payload.reason === "string") state.terminalReason = event.payload.reason;
state.terminalEventSeen = true;
state.awaitingTransition = false;
state.lastTerminalTransition = void 0;
state.currentStep = void 0;
state.pendingStepId = void 0;
}
state.status = status;
}
function assertTerminalRunStatus(state, plan, status, event) {
if (status === "completed") {
if (state.lastTerminalTransition !== "completed") {
throw runtimeError("run_events_illegal", state.runId, "completed requires a selected terminal transition");
}
return;
}
if (status === "cancelled") {
if (state.lastTerminalTransition === "cancelled" && state.status === "running") return;
if ((state.status === "created" || state.status === "preparing") && state.cancelRequested) return;
if (state.status === "cancelling") {
if (!state.currentStep) return;
if (state.currentStep.status === "cancelled" && panelIssuedAttemptsTerminal(state.currentStep)) {
return;
}
if (state.currentStep.effectState === "blocked_uncertain") {
return;
}
}
throw runtimeError("run_events_illegal", state.runId, "cancelled requires a selected terminal or a settled operator cancel");
}
if (status === "failed") {
if (state.lastTerminalTransition === "failed") return;
if (isProvenFailure(state, plan)) return;
if (event.payload.reason === "budget_model_cost" || event.payload.reason === "budget_unmetered_attempts" || event.payload.reason === "budget_step_attempts") {
return;
}
if (state.status === "blocked_uncertain" || state.currentStep?.effectState === "blocked_uncertain") return;
const currentStep = state.currentStep;
if (event.payload.reason === "executing_unrecorded" && currentStep && currentStep.panel.order.length === 1 && panelAttempt(currentStep)?.status === "starting") {
const step = plan?.steps[currentStep.stepId];
if (step?.kind === "gate") {
throw runtimeError("run_events_illegal", state.runId, "executing_unrecorded is illegal on a gate step");
}
if (step && (step.kind === "agent" || step.kind === "moa") && step.assignments.maximum > 1) {
throw runtimeError("run_events_illegal", state.runId, "executing_unrecorded is illegal on a multi-assignment panel");
}
return;
}
throw runtimeError("run_events_illegal", state.runId, "failed requires a selected failed terminal or proven rejection/budget facts");
}
}
function isProvenFailure(state, plan) {
const current = state.currentStep;
if (current) {
const stepTerminal = current.status === "passed" || current.status === "failed" || current.status === "cancelled";
const settled = panelIssuedAttemptsTerminal(current) && panelAssignmentsTerminal(current);
if (stepTerminal && settled) {
const step2 = plan?.steps[current.stepId];
if (step2 && current.status === "failed") {
const joined = kxmJoinAll(step2, current.panel);
if (joined.tag === "rejected" || joined.tag === "conflict") return true;
}
if (plan && current.outcome) {
const selected = plan.steps[current.stepId]?.transitions[current.outcome];
if (selected) {
const edgeKey = `${current.stepId}:${current.outcome}`;
const edgeUsed = (state.edgeTransitions[edgeKey] ?? 0) + 1;
if (selected.maxTransitions !== void 0 && edgeUsed > selected.maxTransitions) return true;
if (state.transitionsUsed + 1 > plan.transitionBudget) return true;
if (selected.to === "step") {
const used2 = state.stepAttempts[selected.target] ?? 0;
const target = plan.steps[selected.target];
if (target && used2 >= target.maxAttempts) return true;
}
}
}
}
return false;
}
if (!plan) return false;
const stepId = state.pendingStepId ?? plan.entryStepId;
const step = plan.steps[stepId];
const used = state.stepAttempts[stepId] ?? 0;
return Boolean(step && used >= step.maxAttempts);
}
function foldDriveOpened(state, event) {
if (state.status !== "running" && state.status !== "blocked_uncertain" && state.status !== "cancelling") {
throw runtimeError("run_events_illegal", state.runId, "run.drive_opened is only legal while running, blocked_uncertain, or cancelling");
}
const driveId = stringPayload(event, "driveId");
const mode = stringPayload(event, "mode");
if (mode !== "simulated" && mode !== "live") {
throw runtimeError("run_events_illegal", state.runId, "run.drive_opened mode must be simulated or live");
}
state.drive = { driveId, mode, openedSequence: event.sequence };
}
function foldCancelRequested(state, event, plan, options) {
if (state.cancelRequested || TERMINAL_RUN.has(state.status)) {
throw runtimeError("run_events_illegal", state.runId, "duplicate run.cancel_requested is not legal");
}
if (event.payload.reason === "budget_run_duration") {
const budget = event.payload.budget;
if (!budget || typeof budget !== "object" || Array.isArray(budget)) {
throw runtimeError("run_events_illegal", state.runId, "budget_run_duration requires a budget payload");
}
const body = budget;
const budgetMs = body.budgetMs;
const elapsedMs = body.elapsedMs;
const source = body.source;
if (typeof budgetMs !== "number" || !Number.isInteger(budgetMs) || budgetMs < 0) {
throw runtimeError("run_events_illegal", state.runId, "budget_run_duration budgetMs is invalid");
}
if (typeof elapsedMs !== "number" || !Number.isInteger(elapsedMs) || elapsedMs < 0) {
throw runtimeError("run_events_illegal", state.runId, "budget_run_duration elapsedMs is invalid");
}
if (source !== "workflow" && source !== "project" && source !== "both") {
throw runtimeError("run_events_illegal", state.runId, "budget_run_duration source is invalid");
}
const expected = effectiveRunDurationBudget(plan?.limits, options.projectLimits);
if (!expected || expected.budgetMs !== budgetMs || expected.source !== source) {
throw runtimeError("run_events_illegal", state.runId, "budget_run_duration budgetMs does not match the plan");
}
if (elapsedMs < budgetMs) {
throw runtimeError("run_events_illegal", state.runId, "budget_run_duration elapsedMs is below budgetMs");
}
}
state.cancelRequested = true;
if (event.commandId) state.cancelCommandId = event.commandId;
}
function requireRunning(state, eventType) {
if (state.status !== "running" && !(state.status === "cancelling" && eventType !== "step.entered")) {
throw runtimeError("run_events_illegal", state.runId, `${eventType} is not legal while the run is ${state.status}`);
}
}
function foldStepEntered(state, plan, event) {
if (state.status !== "running") {
throw runtimeError("run_events_illegal", state.runId, "step.entered is only legal while running");
}
if (state.currentStep) {
throw runtimeError("run_events_illegal", state.runId, "step.entered is illegal while a step is active");
}
const stepId = stringPayload(event, "stepId");
const stepAttempt = integerPayload(event, "stepAttempt");
const expected = state.pendingStepId ?? plan.entryStepId;
if (stepId !== expected) {
throw runtimeError("run_events_illegal", state.runId, `step.entered ${stepId} does not match pending ${expected}`);
}
const step = requireStep(plan, stepId, state.runId);
const used = state.stepAttempts[stepId] ?? 0;
if (used >= step.maxAttempts) {
throw runtimeError("run_events_illegal", state.runId, `step ${stepId} exceeds maxAttempts`);
}
if (stepAttempt !== used + 1) {
throw runtimeError("run_events_illegal", state.runId, `stepAttempt ${stepAttempt} is not the next attempt for ${stepId}`);
}
state.stepAttempts[stepId] = stepAttempt;
state.pendingStepId = void 0;
state.awaitingTransition = false;
state.lastOutcomeEvent = void 0;
state.currentStep = { stepId, stepAttempt, status: "pending", panel: emptyPanel() };
}
function foldStepStatus(state, plan, event) {
requireActiveStep(state, "step.status_changed");
const stepId = stringPayload(event, "stepId");
const status = stringPayload(event, "status");
if (stepId !== state.currentStep.stepId) {
throw runtimeError("run_events_illegal", state.runId, "step.status_changed does not match the active step");
}
if (!STEP_STATUSES.has(status)) {
throw runtimeError("run_events_illegal", state.runId, `illegal step status ${status}`);
}
const allowed = STEP_EDGES[state.currentStep.status];
if (!allowed?.has(status)) {
throw runtimeError("run_events_illegal", state.runId, `illegal step transition ${state.currentStep.status} -> ${status}`);
}
if (status === "passed" || status === "failed" || status === "cancelled") {
const current = state.currentStep;
if (!panelIssuedAttemptsTerminal(current)) {
throw runtimeError("run_events_illegal", state.runId, "terminal step status requires a terminal attempt");
}
const step = plan ? requireStep(plan, current.stepId, state.runId) : void 0;
if (step) {
const joined = kxmJoinAll(step, current.panel);
if (joined.tag === "outcome") {
const expectedStatus = expectedStatusForDeclaredOutcome(step, joined.outcome);
const selected = step.transitions[joined.outcome];
const isCustomOutcomeCancelled = typeof joined.outcome === "string" && joined.outcome !== "passed" && joined.outcome !== "cancelled" && selected?.to === "terminal" && selected.terminalStatus === "cancelled" && status === "cancelled";
if (status === "cancelled" && authorizedCancelStep(state, step, current, status)) {
} else if (status === "passed" && state.cancelRequested && current.panel.order.length < step.assignments.target) {
throw runtimeError("run_events_illegal", state.runId, "cancel before target refill cannot mint a passed step");
} else if (status !== expectedStatus && !isCustomOutcomeCancelled) {
if (expectedStatus === "passed") {
throw runtimeError("run_events_illegal", state.runId, "passed outcome must lead to passed status");
}
if (expectedStatus === "cancelled") {
throw runtimeError("run_events_illegal", state.runId, "cancelled outcome must lead to cancelled status");
}
throw runtimeError("run_events_illegal", state.runId, "non-passed declared outcome must lead to failed status");
}
} else if (joined.tag === "unsatisfied") {
if (!authorizedCancelStep(state, step, current, status)) {
throw runtimeError("run_events_illegal", state.runId, "terminal step status is not legal for this panel join");
}
} else if (joined.tag === "rejected" || joined.tag === "conflict") {
if (status === "cancelled") {
if (!authorizedCancelStep(state, step, current, status)) {
throw runtimeError("run_events_illegal", state.runId, "rejected or conflict cannot cancel the step");
}
} else if (status !== "failed") {
throw runtimeError("run_events_illegal", state.runId, "passed requires recordedOutcome passed");
}
} else if (joined.tag === "cancelled") {
if (!state.cancelRequested) {
throw runtimeError("run_events_illegal", state.runId, "cancelled join requires cancellation authority");
}
if (status !== "cancelled") {
throw runtimeError("run_events_illegal", state.runId, "cancelled join must lead to cancelled status");
}
}
} else if (status === "passed") {
throw runtimeError("run_events_illegal", state.runId, "passed requires recordedOutcome passed");
}
if (state.lastOutcomeEvent) state.awaitingTransition = true;
}
state.currentStep = { ...state.currentStep, status };
}
function foldOutcome(state, plan, event) {
requireActiveStep(state, "step.outcome_recorded");
const stepId = stringPayload(event, "stepId");
const stepAttempt = integerPayload(event, "stepAttempt");
const outcome = stringPayload(event, "outcome");
const current = state.currentStep;
if (stepId !== current.stepId || stepAttempt !== current.stepAttempt) {
throw runtimeError("run_events_illegal", state.runId, "step.outcome_recorded does not match the active attempt");
}
if (!panelIssuedAttemptsTerminal(current) || !panelAssignmentsTerminal(current)) {
throw runtimeError("run_events_illegal", state.runId, "step.outcome_recorded requires a terminal attempt and assignment");
}
if (current.outcome !== void 0) {
throw runtimeError("run_events_illegal", state.runId, "step.outcome_recorded cannot overwrite a recorded outcome");
}
const step = requireStep(plan, stepId, state.runId);
const joined = kxmJoinAll(step, current.panel);
if (joined.tag !== "outcome" || joined.outcome !== outcome) {
throw runtimeError("run_events_illegal", state.runId, "step.outcome_recorded does not match the recorded assignment outcome");
}
if (!step.outcomes.includes(outcome)) {
throw runtimeError("run_events_illegal", state.runId, `outcome ${outcome} is not declared for ${stepId}`);
}
state.currentStep = { ...current, outcome };
state.lastOutcomeEvent = { stepId, stepAttempt, outcome };
}
function foldTransitioned(state, plan, event) {
requireActiveStep(state, "step.transitioned");
const fromStepId = stringPayload(event, "fromStepId");
const outcome = stringPayload(event, "outcome");
const current = state.currentStep;
if (fromStepId !== current.stepId) {
throw runtimeError("run_events_illegal", state.runId, "step.transitioned does not match the active step");
}
if (current.status !== "passed" && current.status !== "failed" && current.status !== "cancelled") {
throw runtimeError("run_events_illegal", state.runId, "step.transitioned requires a settled step status");
}
if (!state.lastOutcomeEvent || state.lastOutcomeEvent.outcome !== outcome || state.lastOutcomeEvent.stepId !== fromStepId) {
throw runtimeError("run_events_illegal", state.runId, "step.transitioned requires a prior matching step.outcome_recorded");
}
if (!panelIssuedAttemptsTerminal(current) || !panelAssignmentsTerminal(current)) {
throw runtimeError("run_events_illegal", state.runId, "step.transitioned requires every panel assignment and issued attempt to be terminal");
}
const step = requireStep(plan, fromStepId, state.runId);
const joined = kxmJoinAll(step, current.panel);
if (joined.tag !== "outcome" || joined.outcome !== outcome) {
throw runtimeError("run_events_illegal", state.runId, "step.transitioned requires a matching joined declared outcome");
}
const selected = step.transitions[outcome];
if (!selected) {
throw runtimeError("run_events_illegal", state.runId, `no compiled transition for ${fromStepId}:${outcome}`);
}
assertTransitionPayload(state.runId, selected, event);
const edgeKey = `${fromStepId}:${outcome}`;
const edgeUsed = (state.edgeTransitions[edgeKey] ?? 0) + 1;
if (selected.maxTransitions !== void 0 && edgeUsed > selected.maxTransitions) {
throw runtimeError("run_events_illegal", state.runId, `edge ${edgeKey} exceeds maxTransitions`);
}
const transitionsUsed = state.transitionsUsed + 1;
if (transitionsUsed > plan.transitionBudget) {
throw runtimeError("run_events_illegal", state.runId, "transitionBudget exceeded");
}
if (selected.to === "step") {
const target = requireStep(plan, selected.target, state.runId);
const targetUsed = state.stepAttempts[selected.target] ?? 0;
if (targetUsed >= target.maxAttempts) {
throw runtimeError("run_events_illegal", state.runId, `target step ${selected.target} has no remaining attempts`);
}
state.pendingStepId = selected.target;
} else {
state.lastTerminalTransition = selected.terminalStatus;
}
state.edgeTransitions[edgeKey] = edgeUsed;
state.transitionsUsed = transitionsUsed;
state.currentStep = void 0;
state.awaitingTransition = false;
state.lastOutcomeEvent = void 0;
}
function assertTransitionPayload(runId, selected, event) {
if (selected.to === "step") {
if (event.payload.toStepId !== selected.target) {
throw runtimeError("run_events_illegal", runId, "step.transitioned toStepId does not match the compiled target");
}
if (event.payload.status !== void 0) {
throw runtimeError("run_events_illegal", runId, "step-target transition must not carry a terminal status");
}
return;
}
if (event.payload.toStepId !== void 0) {
throw runtimeError("run_events_illegal", runId, "terminal step.transitioned must not set toStepId");
}
if (event.payload.status !== selected.terminalStatus) {
throw runtimeError("run_events_illegal", runId, "terminal step.transitioned status does not match the compiled terminal");
}
}
function foldAssignmentCreated(state, plan, event) {
requireActiveStep(state, "assignment.created");
const current = state.currentStep;
if (state.status !== "running" || state.cancelRequested || panelFrozen(current)) {
throw runtimeError("run_events_illegal", state.runId, "assignment.created is not legal after freeze or cancel intent");
}
if (current.panel.order.length >= panelAssignmentBound(plan, current)) {
throw runtimeError("run_events_illegal", state.runId, "assignment.created repeats an assignment");
}
const assignmentId = stringPayload(event, "assignmentId");
const stepId = stringPayload(event, "stepId");
const stepAttempt = integerPayload(event, "stepAttempt");
if (stepId !== current.stepId || stepAttempt !== current.stepAttempt) {
throw runtimeError("run_events_illegal", state.runId, "assignment.created does not match the active step attempt");
}
if (current.panel.assignments[assignmentId]) {
throw runtimeError("run_events_illegal", state.runId, "assignment.created repeats an assignment");
}
state.currentStep = {
...current,
panel: {
order: [...current.panel.order, assignmentId],
assignments: {
...current.panel.assignments,
[assignmentId]: { status: "created", attempts: /* @__PURE__ */ Object.create(null) }
}
}
};
}
function foldAssignmentAdvance(state, plan, event, next) {
requireActiveStep(state, `assignment.${next}`);
const current = state.currentStep;
if (current.panel.order.length === 0) {
throw runtimeError("run_events_illegal", state.runId, `assignment ${next} has no active assignment`);
}
const assignmentId = stringPayload(event, "assignmentId");
const assignment = current.panel.assignments[assignmentId];
if (!assignment) {
throw runtimeError("run_events_illegal", state.runId, "assignment event assignmentId does not match the active assignment");
}
if (!ASSIGNMENT_STATUSES.has(next)) {
throw runtimeError("run_events_illegal", state.runId, `illegal assignment status ${next}`);
}
const step = requireStep(plan, current.stepId, state.runId);
const allowed = ASSIGNMENT_EDGES[assignment.status];
const noStartProof = step.kind === "gate" && assignment.status === "dispatched" && next === "result_recorded" && (current.effectState === "observed-no-start" || current.effectState === "settled-proof");
if (!allowed?.has(next) && !noStartProof) {
throw runtimeError("run_events_illegal", state.runId, `illegal assignment transition ${assignment.status} -> ${next}`);
}
if (next === "dispatched") {
stringPayload(event, "capabilityHash");
}
if (next === "executing" && panelFrozen(current)) {
throw runtimeError("run_events_illegal", state.runId, "assignment.executing is not legal after freeze");
}
if (next === "executing" && state.cancelRequested && step.kind !== "gate") {
throw runtimeError("run_events_illegal", state.runId, "assignment.executing is not legal after cancel intent");
}
let nextAssignment = { ...assignment, status: next, attempts: { ...assignment.attempts } };
if (next === "result_recorded") {
const resultClass = stringPayload(event, "resultClass");
if (!RESULT_CLASSES.has(resultClass)) {
throw runtimeError("run_events_illegal", state.runId, `illegal resultClass ${resultClass}`);
}
const attemptId = assignment.currentAttemptId;
const attempt = attemptId ? assignment.attempts[attemptId] : void 0;
if (resultClass === "outcome") {
const outcome = stringPayload(event, "outcome");
if (!step.outcomes.includes(outcome)) {
throw runtimeError("run_events_illegal", state.runId, `outcome ${outcome} is not declared for ${current.stepId}`);
}
if (step.kind === "gate") {
if (current.effectState !== "settled") {
throw runtimeError("run_events_illegal", state.runId, "gate outcome requires evaluated effect.settled");
}
if (outcome !== current.settledOutcome) {
throw runtimeError("run_events_illegal", state.runId, "gate result outcome does not match settledOutcome");
}
}
if (attemptId && attempt) {
nextAssignment = {
...nextAssignment,
attempts: { ...nextAssignment.attempts, [attemptId]: { ...attempt, resultClass, outcome } }
};
}
} else if (event.payload.outcome !== void 0) {
throw runtimeError("run_events_illegal", state.runId, "non-outcome resultClass must not set outcome");
} else {
if (step.kind === "gate") {
if (resultClass === "outcome_unknown") {
throw runtimeError("run_events_illegal", state.runId, "outcome_unknown is illegal on a gate step");
}
if (current.effectState !== "settled-proof") {
throw runtimeError("run_events_illegal", state.runId, "gate producer_rejected or cancelled requires proof-only effect.settled");
}
if (resultClass === "producer_rejected" && current.observationCompleteness !== "no-start") {
throw runtimeError("run_events_illegal", state.runId, "producer_rejected requires a no-start observation");
}
}
if (attemptId && attempt) {
const producerError = typeof event.payload.producerError === "string" ? event.payload.producerError : void 0;
nextAssignment = {
...nextAssignment,
attempts: {
...nextAssignment.attempts,
[attemptId]: { ...attempt, resultClass, ...producerError !== void 0 ? { producerError } : {} }
}
};
}
}
}
if (next === "terminal") {
const outcome = stringPayload(event, "outcome");
const ownerAttempt = currentAttemptOf(nextAssignment);
const resultClass = ownerAttempt?.resultClass;
if (resultClass === "outcome") {
if (outcome !== ownerAttempt?.outcome) {
throw runtimeError("run_events_illegal", state.runId, "assignment.terminal outcome does not match result_recorded");
}
} else if (resultClass === "outcome_unknown" || resultClass === "producer_rejected") {
if (outcome !== "failed") {
throw runtimeError("run_events_illegal", state.runId, "rejected or unknown results must terminal as failed");
}
} else if (resultClass === "cancelled") {
if (outcome !== "cancelled") {
throw runtimeError("run_events_illegal", state.runId, "cancelled results must terminal as cancelled");
}
} else {
throw runtimeError("run_events_illegal", state.runId, "assignment.terminal requires a prior result_recorded class");
}
const attemptId = nextAssignment.currentAttemptId;
const attempt = attemptId ? nextAssignment.attempts[attemptId] : void 0;
if (attemptId && attempt && attempt.outcome === void 0) {
nextAssignment = {
...nextAssignment,
attempts: { ...nextAssignment.attempts, [attemptId]: { ...attempt, outcome } }
};
}
}
state.currentStep = putAssignment(current, assignmentId, nextAssignment);
}
function foldAttemptCreated(state, event) {
requireActiveStep(state, "attempt.created");
const current = state.currentStep;
if (state.status !== "running" || state.cancelRequested || panelFrozen(current)) {
throw runtimeError("run_events_illegal", state.runId, "attempt.created is not legal after freeze or cancel intent");
}
const assignmentId = stringPayload(event, "assignmentId");
const assignment = current.panel.assignments[assignmentId];
if (!assignment) {
throw runtimeError("run_events_illegal", state.runId, "attempt.created assignmentId does not match");
}
if (assignment.currentAttemptId || Object.keys(assignment.attempts).length >= FOLD_PANEL_BOUND) {
throw runtimeError("run_events_illegal", state.runId, "attempt.created repeats an attempt");
}
const attemptId = stringPayload(event, "attemptId");
if (findPanelAttempt(current.panel, attemptId)) {
throw runtimeError("run_events_illegal", state.runId, "attempt.created repeats an attempt");
}
state.currentStep = putAssignment(current, assignmentId, {
...assignment,
currentAttemptId: attemptId,
attempts: { ...assignment.attempts, [attemptId]: { status: "created" } }
});
}
function foldAttemptStatus(state, plan, event) {
requireActiveStep(state, "attempt.status_changed");
const current = state.currentStep;
if (kxmFoldPanelAttemptIds(current).length === 0) {
throw runtimeError("run_events_illegal", state.runId, "attempt.status_changed has no active attempt");
}
const attemptId = stringPayload(event, "attemptId");
const located = findPanelAttempt(current.panel, attemptId);
if (!located) {
throw runtimeError("run_events_illegal", state.runId, "attempt.status_changed does not match the active attempt");
}
const status = stringPayload(event, "status");
if (!ATTEMPT_STATUSES.has(status)) {
throw runtimeError("run_events_illegal", state.runId, `illegal attempt status ${status}`);
}
const allowed = ATTEMPT_EDGES[located.attempt.status];
const step = requireStep(plan, current.stepId, state.runId);
const noStartSettling = step.kind === "gate" && located.attempt.status === "starting" && status === "settling" && (current.effectState === "observed-no-start" || current.effectState === "settled-proof");
if (!allowed?.has(status) && !noStartSettling) {
throw runtimeError("run_events_illegal", state.runId, `illegal attempt transition ${located.attempt.status} -> ${status}`);
}
if (panelFrozen(current) && (status === "starting" || status === "executing")) {
throw runtimeError("run_events_illegal", state.runId, "attempt start is not legal after freeze");
}
if (state.cancelRequested && status === "starting") {
throw runtimeError("run_events_illegal", state.runId, "attempt start is not legal after cancel intent");
}
if (state.cancelRequested && status === "executing" && step.kind !== "gate") {
throw runtimeError("run_events_illegal", state.runId, "attempt start is not legal after cancel intent");
}
if (status === "starting" && panelInFlightCount(current.panel) + 1 > step.assignments.maxParallel) {
throw runtimeError("run_events_illegal", state.runId, "maxParallel exceeded");
}
state.currentStep = putAssignment(current, located.assignmentId, {
...located.assignment,
attempts: { ...located.assignment.attempts, [attemptId]: { ...located.attempt, status } }
});
}
function requireGateEffect(state, plan, event) {
requireActiveStep(state, event.eventType);
const current = state.currentStep;
const step = requireStep(plan, current.stepId, state.runId);
if (step.kind !== "gate") {
throw runtimeError("run_events_illegal", state.runId, "agent steps reject effect events");
}
assertEffectIdentity(state, event, current);
return current;
}
function assertEffectIdentity(state, event, current) {
const effect = event.payload.effect;
if (!effect || typeof effect !== "object" || Array.isArray(effect)) {
throw runtimeError("run_events_illegal", state.runId, `${event.eventType} is missing effect`);
}
const effectId = effect.id;
if (typeof effectId !== "string" || effectId.length === 0) {
throw runtimeError("run_events_illegal", state.runId, `${event.eventType} is missing effect.id`);
}
const stepId = stringPayload(event, "stepId");
const stepAttempt = integerPayload(event, "stepAttempt");
const assignmentId = stringPayload(event, "assignmentId");
const attemptId = stringPayload(event, "attemptId");
if (stepId !== current.stepId || stepAttempt !== current.stepAttempt || assignmentId !== panelAssignmentId(current) || attemptId !== panelAttemptId(current)) {
throw runtimeError("run_events_illegal", state.runId, `${event.eventType} identity does not match the active attempt`);
}
if (current.effectId && current.effectId !== effectId) {
throw runtimeError("run_events_illegal", state.runId, `${event.eventType} effect.id does not match the active effect`);
}
}
function foldEffectIntent(state, plan, event) {
const current = requireGateEffect(state, plan, event);
if (panelAttempt(current)?.status !== "starting" || current.effectState) {
throw runtimeError("run_events_illegal", state.runId, "effect.intent_recorded requires a starting attempt with no effect");
}
const effectId = event.payload.effect.id;
state.currentStep = { ...current, effectId, effectState: "intent" };
}
function foldEffectDispatched(state, plan, event) {
const current = requireGateEffect(state, plan, event);
if (current.effectState !== "intent") {
throw runtimeError("run_events_illegal", state.runId, "effect.dispatched requires effect intent");
}
if (panelAssignment(current)?.status !== "executing" || panelAttempt(current)?.status !== "executing") {
throw runtimeError("run_events_illegal", state.runId, "effect.dispatched requires executing assignment and attempt");
}
state.currentStep = { ...current, effectState: "dispatched" };
}
function foldEffectObserved(state, plan, event, options) {
const current = requireGateEffect(state, plan, event);
if (current.effectState === "observed-complete" || current.effectState === "observed-no-start" || current.effectState === "observed-unknown") {
throw runtimeError("run_events_illegal", state.runId, "a completed observation cannot be rewritten");
}
if (current.effectState !== "intent" && current.effectState !== "dispatched") {
throw runtimeError("run_events_illegal", state.runId, "effect.observed is not legal from this effect state");
}
const receipt = event.payload.receipt;
if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) {
throw runtimeError("run_events_illegal", state.runId, "effect.observed is missing receipt");
}
const receiptId = receipt.id;
const receiptHash = receipt.hash;
const provider = receipt.provider;
const kind = receipt.kind;
if (typeof receiptId !== "string" || receiptId.length === 0) {
throw runtimeError("run_events_illegal", state.runId, "effect.observed receipt.id is invalid");
}
if (provider !== "kxm-gate") {
throw runtimeError("run_events_illegal", state.runId, "effect.observed receipt.provider must be kxm-gate");
}
const expectedKind = options.gateKind?.(current.stepId);
if (expectedKind && kind !== expectedKind) {
throw runtimeError("run_events_illegal", state.runId, "effect.observed receipt.kind does not match the pinned definition");
}
const looked = options.observationLookup?.(panelAttemptId(current), receiptId);
let effectState = "observed-unknown";
if (looked) {
if (looked.completeness === "complete") {
if (current.effectState === "intent" && expectedKind !== "artifacts-exist") {
throw runtimeError("run_events_illegal", state.runId, "complete command observations require effect.dispatched");
}
effectState = "observed-complete";
} else if (looked.completeness === "no-start") {
if (current.effectState !== "intent") {
throw runtimeError("run_events_illegal", state.runId, "no-start observations are only legal from intent");
}
effectState = "observed-no-start";
} else {
throw runtimeError("run_events_illegal", state.runId, "effect.observed cannot record an incomplete observation");
}
}
state.currentStep = {
...current,
effectState,
observationId: receiptId,
observationCompleteness: effectState === "observed-complete" ? "complete" : effectState === "observed-no-start" ? "no-start" : "unknown",
...typeof receiptHash === "string" ? { observationHash: receiptHash } : {}
};
}
function foldEffectSettled(state, plan, event) {
const current = requireGateEffect(state, plan, event);
const hasOutcome = event.payload.outcome !== void 0;
const hasEvidence = event.payload.evidenceRefs !== void 0;
const receipt = event.payload.receipt;
if (hasOutcome || hasEvidence) {
if (current.effectState !== "observed-complete") {
throw runtimeError("run_events_illegal", state.runId, "evaluated effect.settled requires observed-complete");
}
const outcome = stringPayload(event, "outcome");
if (outcome !== "passed" && outcome !== "implementation-failure" && outcome !== "repro-missing") {
throw runtimeError("run_events_illegal", state.runId, "evaluated effect.settled outcome is invalid");
}
const step = requireStep(plan, current.stepId, state.runId);
if (!step.outcomes.includes(outcome)) {
throw runtimeError("run_events_illegal", state.runId, `outcome ${outcome} is not declared for ${current.stepId}`);
}
const refs = event.payload.evidenceRefs;
if (!Array.isArray(refs) || refs.length !== 1) {
throw runtimeError("run_events_illegal", state.runId, "evaluated effect.settled requires exactly one evidenceRef");
}
const ref = refs[0];
if (typeof ref.id !== "string" || ref.kind !== "gate" || typeof ref.hash !== "string" || !/^sha256:[a-f0-9]{64}$/.test(ref.hash) || ref.status !== "settled") {
throw runtimeError("run_events_illegal", state.runId, "evaluated effect.settled evidenceRef is invalid");
}
state.currentStep = {
...current,
effectState: "settled",
settledOutcome: outcome,
evidenceRefs: [{ id: ref.id, kind: "gate", hash: ref.hash, status: "settled" }]
};
return;
}
if (current.effectState !== "observed-complete" && current.effectState !== "observed-no-start") {
throw runtimeError("run_events_illegal", state.runId, "proof-only effect.settled requires a prior observation");
}
if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) {
throw runtimeError("run_events_illegal", state.runId, "proof-only effect.settled is missing observation receipt");
}
const receiptId = receipt.id;
const receiptHash = receipt.hash;
if (receiptId !== current.observationId || current.observationHash && receiptHash !== current.observationHash) {
throw runtimeError("run_events_illegal", state.runId, "proof-only effect.settled does not bind the prior observation");
}
state.currentStep = { ...current, effectState: "settled-proof" };
}
function foldEffectUncertain(state, plan, event) {
const current = requireGateEffect(state, plan, event);
if (current.effectState === "observed-complete" || current.effectState === "observed-no-start" || current.effectState === "observed-unknown") {
throw runtimeError("run_events_illegal", state.runId, "blocked_uncertain after an observation is illegal");
}
if (current.effectState !== "intent" && current.effectState !== "dispatched") {
throw runtimeError("run_events_illegal", state.runId, "effect.blocked_uncertain is not legal from this effect state");
}
const reason = stringPayload(event, "reason");
const allowed = /* @__PURE__ */ new Set(["timeout", "cancel", "stream-error", "stop-error", "lost-close", "signal-termination", "recording-error"]);
if (!allowed.has(reason)) {
throw runtimeError("run_events_illegal", state.runId, "effect.blocked_uncertain reason is invalid");
}
const receipt = event.payload.receipt;
if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) {
throw runtimeError("run_events_illegal", state.runId, "effect.blocked_uncertain is missing receipt");
}
const receiptId = receipt.id;
if (typeof receiptId !== "string" || receiptId.length === 0) {
throw runtimeError("run_events_illegal", state.runId, "effect.blocked_uncertain receipt.id is invalid");
}
state.currentStep = { ...current, effectState: "blocked_uncertain", observationId: receiptId };
}
function requireActiveStep(state, eventType) {
requireRunning(state, eventType);
if (!state.currentStep) {
throw runtimeError("run_events_illegal", state.runId, `${eventType} requires an active step`);
}
}
function requireStep(plan, stepId, runId) {
const step = plan.steps[stepId];
if (!step) throw runtimeError("run_events_illegal", runId, `unknown step ${stepId}`);
return step;
}
function stringPayload(event, field) {
const value = event.payload[field];
if (typeof value !== "string" || value.length === 0) {
throw runtimeError("run_events_illegal", event.runId, `${event.eventType} is missing ${field}`);
}
return value;
}
function integerPayload(event, field) {
const value = event.payload[field];
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
throw runtimeError("run_events_illegal", event.runId, `${event.eventType} is missing a valid ${field}`);
}
return value;
}
function freezePanel(panel) {
const assignments = /* @__PURE__ */ Object.create(null);
for (const assignmentId of Object.keys(panel.assignments).sort()) {
const assignment = panel.assignments[assignmentId];
const attempts = /* @__PURE__ */ Object.create(null);
for (const attemptId of Object.keys(assignment.attempts).sort()) {
attempts[attemptId] = Object.freeze(omitUndefined({ ...assignment.attempts[attemptId] }));
}
assignments[assignmentId] = Object.freeze(omitUndefined({
status: assignment.status,
...assignment.currentAttemptId !== void 0 ? { currentAttemptId: assignment.currentAttemptId } : {},
attempts: Object.freeze(attempts)
}));
}
return Object.freeze({
order: Object.freeze([...panel.order]),
assignments: Object.freeze(assignments)
});
}
function freezeCurrentStep(current) {
const panel = freezePanel(current.panel);
const assignmentId = panel.order.length === 1 ? panel.order[0] : void 0;
const assignment = assignmentId ? panel.assignments[assignmentId] : void 0;
const attemptId = assignment?.currentAttemptId;
const attempt = attemptId ? assignment?.attempts[attemptId] : void 0;
return Object.freeze(omitUndefined({
stepId: current.stepId,
stepAttempt: current.stepAttempt,
status: current.status,
panel,
...assignmentId !== void 0 ? { assignmentId } : {},
...assignment ? { assignmentStatus: assignment.status } : {},
...attemptId !== void 0 ? { attemptId } : {},
...attempt ? { attemptStatus: attempt.status } : {},
...current.outcome !== void 0 ? { outcome: current.outcome } : {},
...current.effectId !== void 0 ? { effectId: current.effectId } : {},
...current.effectState !== void 0 ? { effectState: current.effectState } : {},
...current.observationId !== void 0 ? { observationId: current.observationId } : {},
...current.observationHash !== void 0 ? { observationHash: current.observationHash } : {},
...current.observationCompleteness !== void 0 ? { observationCompleteness: current.observationCompleteness } : {},
...current.settledOutcome !== void 0 ? { settledOutcome: current.settledOutcome } : {},
...current.evidenceRefs !== void 0 ? { evidenceRefs: current.evidenceRefs } : {}
}));
}
function freezeState(state) {
const frozen = {
schema: KXM_RUN_STATE_SCHEMA,
runId: state.runId,
status: state.status,
...state.runPlanHash !== void 0 ? { runPlanHash: state.runPlanHash } : {},
...state.pendingStepId !== void 0 ? { pendingStepId: state.pendingStepId } : {},
...state.currentStep !== void 0 ? { currentStep: freezeCurrentStep(state.currentStep) } : {},
stepAttempts: Object.freeze({ ...state.stepAttempts }),
edgeTransitions: Object.freeze({ ...state.edgeTransitions }),
transitionsUsed: state.transitionsUsed,
cancelRequested: state.cancelRequested,
...state.terminalReason !== void 0 ? { terminalReason: state.terminalReason } : {},
...state.terminalReason !== void 0 && state.status === "failed" ? { failureReason: state.terminalReason } : {},
...state.drive !== void 0 ? { drive: Object.freeze({ ...state.drive }) } : {},
...state.runningSince !== void 0 ? { runningSince: state.runningSince } : {}
};
return Object.freeze(frozen);
}
function omitUndefined(value) {
const copy = { ...value };
for (const key of Object.keys(copy)) {
if (copy[key] === void 0) delete copy[key];
}
return copy;
}
function isTerminalRunStatus(status) {
return TERMINAL_RUN.has(status);
}
// plugins/kxm/src/engine-plan.ts
import { createHash as createHash8 } from "node:crypto";
// plugins/kxm/src/engine-compile.ts
var KXM_COMPILED_WORKFLOW_SCHEMA = "kxm.compiled-workflow.v1";
var WORKFLOW_SCHEMA = "kxm.workflow.v1";
var STEP_ID_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/;
var SUPPORTED_STEP_KINDS = /* @__PURE__ */ new Set(["agent", "moa", "gate", "approval", "wait"]);
var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
var JOIN_STRATEGIES = /* @__PURE__ */ new Set(["all", "all-settled", "quorum", "first-success"]);
var EVIDENCE_KINDS = /* @__PURE__ */ new Set(["assignment-result", "gate", "receipt", "approval", "artifact"]);
var REPOSITORY_ACCESS = /* @__PURE__ */ new Set(["none", "read", "write"]);
var DISTINCT_BY = /* @__PURE__ */ new Set(["provider", "model", "profile"]);
var BANNED_RUNTIME_HINT = "not yet supported";
var KxmEngineCompileError = class extends Error {
issues;
constructor(issues) {
const sorted = sortIssues4(issues);
super(sorted.map((issue4) => `${issue4.workflowId}: ${issue4.code}: ${issue4.message}`).join("\n"));
this.name = "KxmEngineCompileError";
this.issues = sorted;
}
};
function compileKxmWorkflow(input) {
const sink = { workflowId: input.id, issues: [] };
const value = input.value;
if (value.schema !== WORKFLOW_SCHEMA) {
pushIssue(sink, { code: "workflow_schema_unsupported", message: "schema is not kxm.workflow.v1" });
}
const rawSteps = valuesOf2(value, "steps").map(objectValue2).filter((step) => Boolean(step));
if (rawSteps.length === 0) {
pushIssue(sink, { code: "steps_empty", message: "workflow has no steps" });
}
const stepIndex = /* @__PURE__ */ new Map();
for (const [index, step] of rawSteps.entries()) {
const id = stringValue2(step.id);
if (!id || !isStepId(id)) {
pushIssue(sink, { code: "step_id_invalid", message: "step id is invalid", ...id ? { stepId: id } : {} });
continue;
}
if (stepIndex.has(id)) {
pushIssue(sink, { code: "step_id_duplicate", stepId: id, message: `step ${id} is duplicated` });
continue;
}
stepIndex.set(id, index);
}
const limitsObject = objectValue2(value.limits);
const limits = compileLimits(limitsObject, sink);
const requirePlanHash = names2(value.requirePlanHash);
const compiledSteps = [];
let hasBackEdges = false;
for (const [index, step] of rawSteps.entries()) {
const compiled = compileStep(step, index, stepIndex, requirePlanHash, sink);
if (!compiled) continue;
compiledSteps.push(compiled);
if (Object.values(compiled.transitions).some((transition2) => transition2.to === "step" && transition2.edge === "back")) {
hasBackEdges = true;
}
}
if (hasBackEdges && typeof limitsObject?.maxTransitions !== "number") {
pushIssue(sink, { code: "workflow_cycle_unbounded", message: "workflow with back-edges requires limits.maxTransitions" });
}
const reproOracle = compileOracle("reproOracle", objectValue2(value.reproOracle), compiledSteps, sink);
const planHash = compileOracle("planHash", objectValue2(value.planHash), compiledSteps, sink);
for (const stageId of requirePlanHash) {
if (!stepIndex.has(stageId)) {
pushIssue(sink, { code: "plan_hash_stage_unknown", message: `requirePlanHash references unknown stage ${stageId}` });
}
}
if (sink.issues.length > 0) throw new KxmEngineCompileError(sink.issues);
const order = compiledSteps.map((step) => step.id);
const steps = /* @__PURE__ */ Object.create(null);
for (const step of compiledSteps) steps[step.id] = step;
const entryStepId = order[0];
if (!entryStepId) throw new KxmEngineCompileError(sink.issues);
const coordinator = stringValue2(value.coordinator) ?? "coordinator";
const transitionBudget = limits.maxTransitions ?? order.length;
const plan = {
schema: KXM_COMPILED_WORKFLOW_SCHEMA,
workflowId: input.id,
...input.logicalPath !== void 0 ? { sourcePath: input.logicalPath } : {},
coordinator,
limits,
transitionBudget,
hasBackEdges,
entryStepId,
order,
steps,
...reproOracle ? { reproOracle } : {},
...planHash ? { planHash } : {},
requirePlanHash: [...requirePlanHash]
};
return deepFreeze(plan);
}
function compileLimits(limits, sink) {
if (!limits) return {};
const compiled = {};
if (limits.maxTransitions !== void 0) {
if (isCount(limits.maxTransitions)) compiled.maxTransitions = limits.maxTransitions;
else pushIssue(sink, { code: "count_invalid", message: "limits.maxTransitions must be an integer >= 1" });
}
if (limits.maxRunDurationMs !== void 0) {
if (isDuration(limits.maxRunDurationMs)) compiled.maxRunDurationMs = limits.maxRunDurationMs;
else pushIssue(sink, { code: "duration_invalid", message: "limits.maxRunDurationMs must be an integer >= 0" });
}
if (limits.maxAgentTimeMs !== void 0) {
if (isDuration(limits.maxAgentTimeMs)) compiled.maxAgentTimeMs = limits.maxAgentTimeMs;
else pushIssue(sink, { code: "duration_invalid", message: "limits.maxAgentTimeMs must be an integer >= 0" });
}
if (limits.maxModelCost !== void 0) {
if (isCost(limits.maxModelCost)) compiled.maxModelCost = limits.maxModelCost;
else pushIssue(sink, { code: "cost_invalid", message: "limits.maxModelCost must be a finite number > 0" });
}
if (limits.currency !== void 0) {
if (typeof limits.currency === "string") compiled.currency = limits.currency;
}
return compiled;
}
function compileStep(step, index, stepIndex, requirePlanHash, sink) {
const id = stringValue2(step.id);
if (!id || !isStepId(id) || stepIndex.get(id) !== index) return void 0;
const kind = stringValue2(step.kind);
if (kind === "workflow") {
pushIssue(sink, { code: "step_kind_reserved", stepId: id, message: `kind workflow is ${BANNED_RUNTIME_HINT}` });
return void 0;
}
if (!kind || !SUPPORTED_STEP_KINDS.has(kind)) {
pushIssue(sink, { code: "step_kind_unknown", stepId: id, message: `kind ${String(kind)} is unknown` });
return void 0;
}
const agent = stringValue2(step.agent);
const gate = stringValue2(step.gate);
const signal = stringValue2(step.signal);
if ((kind === "agent" || kind === "moa") && !agent) {
pushIssue(sink, { code: "step_agent_missing", stepId: id, message: `${id} is missing agent` });
}
if (kind === "gate" && !gate) {
pushIssue(sink, { code: "step_gate_missing", stepId: id, message: `${id} is missing gate` });
}
if (kind === "wait" && !signal) {
pushIssue(sink, { code: "step_signal_missing", stepId: id, message: `${id} is missing signal` });
}
if (step.expect !== void 0 && (kind !== "gate" || step.expect !== "pass" && step.expect !== "fail")) {
pushIssue(sink, { code: "gate_expect_invalid", stepId: id, message: "expect is gate-only pass or fail" });
}
if (kind === "gate" && Object.keys(objectValue2(step.on) ?? {}).some((outcome) => outcome === "implementation_failure" || outcome === "repro_missing")) {
pushIssue(sink, { code: "gate_outcome_renamed", stepId: id, message: "use implementation-failure and repro-missing" });
}
const maxAttempts = compileCountField(step.maxAttempts, 1, `${id}.maxAttempts`, id, sink);
const timeoutMs = compileOptionalDuration(step.timeoutMs, `${id}.timeoutMs`, id, sink);
const assignments = compileAssignments(step, id, agent, sink);
const join27 = compileJoin(step, id, sink);
const requiredEvidence = compileEvidence(step, id, sink);
const transitions = compileTransitions(step, id, index, stepIndex, sink);
const outcomes = Object.keys(transitions).sort(compareCodeUnits5);
const orderedTransitions = /* @__PURE__ */ Object.create(null);
for (const outcome of outcomes) {
const transition2 = transitions[outcome];
if (transition2) orderedTransitions[outcome] = transition2;
}
const description = stringValue2(step.description);
const instructions = stringValue2(step.instructions);
const base = {
id,
index,
...description !== void 0 ? { description } : {},
...instructions !== void 0 ? { instructions } : {},
maxAttempts,
...timeoutMs !== void 0 ? { timeoutMs } : {},
safeSpeculation: step.safeSpeculation === true,
repositories: compileRepositories(step.repositories),
...isJsonObject3(step.tools) ? { tools: cloneJsonObject(step.tools) } : {},
secrets: compileSecrets(step.secrets),
...step.model !== void 0 ? { model: cloneJsonValue(step.model) } : {},
requiredEvidence,
outcomes,
transitions: orderedTransitions,
requiresPlanHash: requirePlanHash.includes(id),
assignments,
join: join27
};
if (kind === "agent" || kind === "moa") {
if (!agent) return void 0;
return { ...base, kind, agent };
}
if (kind === "gate") {
if (!gate) return void 0;
return { ...base, kind, gate, expect: step.expect === "fail" ? "fail" : "pass" };
}
if (kind === "wait") {
if (!signal) return void 0;
return { ...base, kind, signal };
}
return { ...base, kind: "approval" };
}
function compileAssignments(step, stepId, primaryAgentId, sink) {
const assignment = objectValue2(step.assignments);
const declaredAgents = assignment ? names2(assignment.allowedAgents) : [];
const allowedAgents = declaredAgents.length > 0 ? declaredAgents : primaryAgentId ? [primaryAgentId] : [];
const minimum = compileCountField(assignment?.minimum, 1, `${stepId}.assignments.minimum`, stepId, sink);
const target = compileCountField(assignment?.target, minimum, `${stepId}.assignments.target`, stepId, sink);
const maximum = compileCountField(assignment?.maximum, target, `${stepId}.assignments.maximum`, stepId, sink);
const maxParallel = compileCountField(assignment?.maxParallel, maximum, `${stepId}.assignments.maxParallel`, stepId, sink);
const maxAttemptsPerAssignment = compileCountField(
assignment?.maxAttemptsPerAssignment,
1,
`${stepId}.assignments.maxAttemptsPerAssignment`,
stepId,
sink
);
const maxWriteRepositories = compileOptionalCount(
assignment?.maxWriteRepositories,
`${stepId}.assignments.maxWriteRepositories`,
stepId,
sink
);
const distinctBy = names2(assignment?.distinctBy).filter((value) => DISTINCT_BY.has(value));
return {
allowedAgents: [...allowedAgents],
minimum,
target,
maximum,
maxParallel,
maxAttemptsPerAssignment,
...maxWriteRepositories !== void 0 ? { maxWriteRepositories } : {},
distinctBy
};
}
function compileJoin(step, stepId, sink) {
const join27 = objectValue2(step.join);
if (!join27) return { strategy: "all" };
const declared = stringValue2(join27.strategy);
const strategy = declared && JOIN_STRATEGIES.has(declared) ? declared : "all";
const minimumPassed = compileOptionalCount(join27.minimumPassed, `${stepId}.join.minimumPassed`, stepId, sink);
const compiled = {
strategy,
...minimumPassed !== void 0 ? { minimumPassed } : {},
...typeof join27.cancelRemaining === "boolean" ? { cancelRemaining: join27.cancelRemaining } : {}
};
return compiled;
}
function compileEvidence(step, stepId, sink) {
const evidence = [];
const seen = /* @__PURE__ */ new Set();
for (const candidate of valuesOf2(step, "requiredEvidence")) {
const requirement = objectValue2(candidate);
if (!requirement) continue;
const key = stringValue2(requirement.key);
if (!key) continue;
if (seen.has(key)) {
pushIssue(sink, { code: "evidence_key_duplicate", stepId, message: `${stepId} evidence key ${key} is duplicated` });
continue;
}
seen.add(key);
const kind = stringValue2(requirement.kind);
if (!kind || !EVIDENCE_KINDS.has(kind)) continue;
const minimum = compileCountField(requirement.minimum, 1, `${stepId}.${key}.minimum`, stepId, sink);
const producerPolicy = objectValue2(requirement.producerPolicy);
const compiled = {
key,
kind,
minimum,
reusableAcrossAttempts: requirement.reusableAcrossAttempts === true,
...producerPolicy ? { producerPolicy: compileProducerPolicy(producerPolicy, stepId, key, sink) } : {}
};
evidence.push(compiled);
}
return evidence;
}
function compileProducerPolicy(policy, stepId, key, sink) {
const minimumProducers = compileCountField(
policy.minimumProducers,
1,
`${stepId}.${key}.producerPolicy.minimumProducers`,
stepId,
sink
);
const degradation = objectValue2(policy.degradation);
const degradationMinimum = compileOptionalCount(
degradation?.minimumProducers,
`${stepId}.${key}.producerPolicy.degradation.minimumProducers`,
stepId,
sink
);
return {
minimumProducers,
eligibleAgents: names2(policy.eligibleAgents),
acceptedStatuses: ["passed"],
...degradationMinimum !== void 0 ? { degradation: { minimumProducers: degradationMinimum } } : {}
};
}
function compileTransitions(step, stepId, index, stepIndex, sink) {
const outcomes = objectValue2(step.on);
const compiled = /* @__PURE__ */ Object.create(null);
if (!outcomes || Object.keys(outcomes).length === 0) {
pushIssue(sink, { code: "transitions_missing", stepId, message: `${stepId} has no declared transitions` });
return compiled;
}
for (const [outcome, raw] of Object.entries(outcomes)) {
const parsed = parseTransition(raw);
const maxTransitions = compileOptionalCount(
parsed.maxTransitions,
`${stepId}.${outcome}.maxTransitions`,
stepId,
sink,
outcome
);
if (parsed.target === "$terminal") {
const status = parsed.terminalStatus;
if (status === void 0) {
pushIssue(sink, {
code: "transition_terminal_status_missing",
stepId,
outcome,
message: `${stepId}.${outcome} terminal transition requires terminalStatus`
});
continue;
}
if (!TERMINAL_STATUSES.has(status)) {
pushIssue(sink, {
code: "transition_terminal_status_invalid",
stepId,
outcome,
message: `${stepId}.${outcome} terminalStatus is invalid`
});
continue;
}
compiled[outcome] = {
to: "terminal",
terminalStatus: status,
...maxTransitions !== void 0 ? { maxTransitions } : {}
};
continue;
}
if (parsed.terminalStatus !== void 0) {
pushIssue(sink, {
code: "transition_terminal_status_unexpected",
stepId,
outcome,
message: `${stepId}.${outcome} step target must not declare terminalStatus`
});
}
if (!parsed.target || !stepIndex.has(parsed.target)) {
pushIssue(sink, {
code: "transition_target_unknown",
stepId,
outcome,
message: `${stepId}.${outcome} references unknown target ${String(parsed.target)}`
});
continue;
}
const targetIndex = stepIndex.get(parsed.target);
const back = targetIndex <= index;
if (back && maxTransitions === void 0 && parsed.maxTransitions === void 0) {
pushIssue(sink, {
code: "back_edge_unbounded",
stepId,
outcome,
message: `${stepId}.${outcome} back-edge requires maxTransitions`
});
}
compiled[outcome] = {
to: "step",
target: parsed.target,
edge: back ? "back" : "forward",
...maxTransitions !== void 0 ? { maxTransitions } : {}
};
}
return compiled;
}
function parseTransition(value) {
if (typeof value === "string") return { target: value };
const object = objectValue2(value);
if (!object) return {};
const target = stringValue2(object.target);
const terminalStatus = stringValue2(object.terminalStatus);
return {
...target ? { target } : {},
...object.maxTransitions !== void 0 ? { maxTransitions: object.maxTransitions } : {},
...terminalStatus ? { terminalStatus } : {}
};
}
function compileOracle(field, oracle, steps, sink) {
if (!oracle) return void 0;
const stageId = stringValue2(oracle.stageId);
const evidenceKey = stringValue2(oracle.evidenceKey);
const step = stageId === void 0 ? void 0 : steps.find((candidate) => candidate.id === stageId);
if (!stageId || !step) {
pushIssue(sink, { code: "oracle_stage_unknown", message: `${field} references unknown stage ${String(stageId)}` });
return void 0;
}
if (!evidenceKey || !step.requiredEvidence.some((item) => item.key === evidenceKey)) {
pushIssue(sink, {
code: "oracle_evidence_unknown",
message: `${field} references undeclared evidence ${String(evidenceKey)} in ${stageId}`
});
return void 0;
}
return { stageId, evidenceKey };
}
function compileRepositories(value) {
const source = objectValue2(value) ?? {};
const repositories = {};
for (const [id, access] of Object.entries(source)) {
if (typeof access === "string" && REPOSITORY_ACCESS.has(access)) {
repositories[id] = access;
}
}
return repositories;
}
function compileSecrets(value) {
if (!Array.isArray(value)) return [];
return value.map(objectValue2).filter((entry) => Boolean(entry)).map(cloneJsonObject);
}
function compileCountField(value, fallback, path, stepId, sink) {
if (value === void 0) return fallback;
if (isCount(value)) return value;
pushIssue(sink, { code: "count_invalid", stepId, message: `${path} must be an integer >= 1` });
return fallback;
}
function compileOptionalCount(value, path, stepId, sink, outcome) {
if (value === void 0) return void 0;
if (isCount(value)) return value;
pushIssue(sink, {
code: "count_invalid",
stepId,
...outcome ? { outcome } : {},
message: `${path} must be an integer >= 1`
});
return void 0;
}
function compileOptionalDuration(value, path, stepId, sink) {
if (value === void 0) return void 0;
if (isDuration(value)) return value;
pushIssue(sink, { code: "duration_invalid", stepId, message: `${path} must be an integer >= 0` });
return void 0;
}
function isCount(value) {
return typeof value === "number" && Number.isInteger(value) && value >= 1;
}
function isDuration(value) {
return typeof value === "number" && Number.isInteger(value) && value >= 0;
}
function isCost(value) {
return typeof value === "number" && Number.isFinite(value) && value > 0;
}
function isStepId(value) {
return value.length >= 1 && value.length <= 64 && STEP_ID_PATTERN.test(value);
}
function isJsonObject3(value) {
return value !== void 0 && value !== null && typeof value === "object" && !Array.isArray(value);
}
function objectValue2(value) {
return isJsonObject3(value) ? value : void 0;
}
function stringValue2(value) {
return typeof value === "string" ? value : void 0;
}
function valuesOf2(object, field) {
const value = object[field];
return Array.isArray(value) ? value : [];
}
function names2(value) {
return Array.isArray(value) ? value.filter((candidate) => typeof candidate === "string") : [];
}
function cloneJsonValue(value) {
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
if (Array.isArray(value)) return value.map((entry) => cloneJsonValue(entry));
return cloneJsonObject(isJsonObject3(value) ? value : {});
}
function cloneJsonObject(value) {
const copy = {};
for (const [key, child] of Object.entries(value)) copy[key] = cloneJsonValue(child);
return copy;
}
function deepFreeze(value) {
if (value === null || typeof value !== "object") return value;
if (Array.isArray(value)) {
for (const entry of value) deepFreeze(entry);
} else {
for (const entry of Object.values(value)) deepFreeze(entry);
}
return Object.freeze(value);
}
function compareCodeUnits5(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
function compareOptional(left, right) {
if (left === right) return 0;
if (left === void 0) return -1;
if (right === void 0) return 1;
return compareCodeUnits5(left, right);
}
function sortIssues4(issues) {
return [...issues].sort((left, right) => {
const byStep = compareOptional(left.stepId, right.stepId);
if (byStep !== 0) return byStep;
const byOutcome = compareOptional(left.outcome, right.outcome);
if (byOutcome !== 0) return byOutcome;
return compareCodeUnits5(left.code, right.code);
});
}
function pushIssue(sink, issue4) {
sink.issues.push({ workflowId: sink.workflowId, ...issue4 });
}
// plugins/kxm/src/engine-plan.ts
var KXM_RUN_PLAN_SCHEMA = "kxm.run-plan.v2";
var SUPPORTED_KINDS = /* @__PURE__ */ new Set(["agent", "moa", "gate", "approval", "wait"]);
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
var JOIN_STRATEGIES2 = /* @__PURE__ */ new Set(["all", "all-settled", "quorum", "first-success"]);
var EVIDENCE_KINDS2 = /* @__PURE__ */ new Set(["assignment-result", "gate", "receipt", "approval", "artifact"]);
var REPOSITORY_ACCESS2 = /* @__PURE__ */ new Set(["none", "read", "write"]);
var DISTINCT_BY2 = /* @__PURE__ */ new Set(["provider", "model", "profile"]);
var ENVELOPE_REQUIRED = ["schema", "runId", "projectId", "homeRuntimeId", "workflowId", "revisions", "projectLimits", "plan", "gates"];
var GATES_REQUIRED = ["registry", "definitions", "controlRoot"];
var REGISTRY_PIN_REQUIRED = ["schema", "hash"];
var CONTROL_ROOT_REQUIRED = ["repositoryId", "projectKey"];
var GATE_REGISTRY_SCHEMA = "kxm.gate-registry.v1";
var REVISION_REQUIRED = ["config", "executorPolicy", "toolPolicy", "memory"];
var PROJECT_LIMIT_REQUIRED = ["maxConcurrentRuns"];
var PROJECT_LIMIT_OPTIONAL = ["maxRunDurationMs", "maxAgentTimeMs", "agentStepTimeoutMs"];
var PLAN_REQUIRED = ["schema", "workflowId", "coordinator", "limits", "transitionBudget", "hasBackEdges", "entryStepId", "order", "steps", "requirePlanHash"];
var PLAN_OPTIONAL = ["sourcePath", "reproOracle", "planHash"];
var LIMIT_OPTIONAL = ["maxTransitions", "maxRunDurationMs", "maxAgentTimeMs", "maxModelCost", "currency"];
var STEP_REQUIRED = [
"id",
"index",
"kind",
"maxAttempts",
"safeSpeculation",
"repositories",
"secrets",
"requiredEvidence",
"outcomes",
"transitions",
"requiresPlanHash",
"assignments",
"join"
];
var STEP_OPTIONAL = ["description", "instructions", "timeoutMs", "tools", "model"];
var ASSIGNMENT_REQUIRED = ["allowedAgents", "minimum", "target", "maximum", "maxParallel", "maxAttemptsPerAssignment", "distinctBy"];
var ASSIGNMENT_OPTIONAL = ["maxWriteRepositories"];
var JOIN_REQUIRED = ["strategy"];
var JOIN_OPTIONAL = ["minimumPassed", "cancelRemaining"];
var EVIDENCE_REQUIRED = ["key", "kind", "minimum", "reusableAcrossAttempts"];
var EVIDENCE_OPTIONAL = ["producerPolicy"];
function kxmSha256(input) {
return `sha256:${createHash8("sha256").update(input, "utf8").digest("hex")}`;
}
function kxmStepAskSha256(plan, stepId, agentId) {
const step = Object.hasOwn(plan.steps, stepId) ? plan.steps[stepId] : void 0;
if (!step) throw runtimeError("run_plan_corrupt", plan.workflowId, `compiled plan is missing step ${stepId}`);
return kxmSha256(kxmCanonicalJson({
v: 1,
workflowId: plan.workflowId,
stepId,
kind: step.kind,
agentId,
instructions: step.instructions ?? null,
outcomes: [...step.outcomes],
requiredEvidence: step.requiredEvidence.map((entry) => entry.key)
}));
}
function kxmAttemptFinalOutcome(step, settled) {
if (settled.resultClass !== "outcome") return "failed";
const outcome = settled.outcome;
const transition2 = outcome !== void 0 && Object.hasOwn(step.transitions, outcome) ? step.transitions[outcome] : void 0;
if (!transition2) return "failed";
if (transition2.to === "terminal") return transition2.terminalStatus === "completed" ? void 0 : "failed";
return transition2.edge === "back" ? "blocked" : void 0;
}
function hashKxmRunPlanEnvelope(envelope2) {
return kxmSha256(kxmCanonicalJson(envelope2));
}
function freezeKxmCompiledPlan(plan) {
const steps = /* @__PURE__ */ Object.create(null);
for (const id of plan.order) {
const step = plan.steps[id];
if (!step) throw runtimeError("run_plan_corrupt", plan.workflowId, `compiled plan is missing step ${id}`);
steps[id] = freezeStep(step);
}
return deepFreeze2({
...plan,
steps,
order: [...plan.order],
requirePlanHash: [...plan.requirePlanHash]
});
}
function freezeStep(step) {
const transitions = /* @__PURE__ */ Object.create(null);
for (const outcome of step.outcomes) {
const transition2 = step.transitions[outcome];
if (!transition2) throw runtimeError("run_plan_corrupt", step.id, `compiled plan is missing transition ${outcome}`);
transitions[outcome] = { ...transition2 };
}
const repositories = /* @__PURE__ */ Object.create(null);
for (const [id, access] of Object.entries(step.repositories)) repositories[id] = access;
return deepFreeze2({
...step,
outcomes: [...step.outcomes],
transitions,
repositories,
secrets: step.secrets.map((entry) => ({ ...entry })),
requiredEvidence: step.requiredEvidence.map((entry) => ({ ...entry })),
assignments: {
...step.assignments,
allowedAgents: [...step.assignments.allowedAgents],
distinctBy: [...step.assignments.distinctBy]
},
join: { ...step.join }
});
}
function parseKxmRunPlanEnvelope(raw, run, expectedHash) {
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw runtimeError("run_plan_corrupt", run.runId, "run plan envelope is not JSON");
}
const envelope2 = parseEnvelope(parsed, run);
const hash = hashKxmRunPlanEnvelope(envelope2);
if (hash !== expectedHash) {
throw runtimeError("run_plan_corrupt", run.runId, "run plan envelope hash does not match");
}
return envelope2;
}
function rehydrateKxmCompiledPlanFromStore(store, run) {
return loadPinnedEnvelope(store, run).plan;
}
function loadKxmRunPlanEnvelope(store, run) {
return loadPinnedEnvelope(store, run);
}
function loadPinnedEnvelope(store, run) {
const row = store.runPlan(run.runId);
if (!row) throw runtimeError("run_plan_missing", run.runId, "run has no pinned plan");
const events = store.events(run.runId, 0, row.pinnedSequence);
const pinEvent = events.find((event) => event.sequence === row.pinnedSequence);
const eventHash = pinEvent?.payload.runPlanHash;
if (typeof eventHash !== "string" || eventHash !== row.runPlanHash) {
throw runtimeError("run_plan_corrupt", run.runId, "pinned runPlanHash does not match the plan row");
}
return parseKxmRunPlanEnvelope(row.envelope, run, row.runPlanHash);
}
function parseEnvelope(parsed, run) {
const value = asObject(parsed, run.runId, "run plan envelope");
assertExactKeys(value, ENVELOPE_REQUIRED, [], run.runId, "run plan envelope");
if (value.schema !== KXM_RUN_PLAN_SCHEMA) {
throw runtimeError("run_plan_corrupt", run.runId, "schema is not kxm.run-plan.v2");
}
const runId = asString(value.runId, run.runId, "runId");
const projectId = asString(value.projectId, run.runId, "projectId");
const homeRuntimeId = asString(value.homeRuntimeId, run.runId, "homeRuntimeId");
const workflowId = asString(value.workflowId, run.runId, "workflowId");
if (runId !== run.runId || projectId !== run.projectId || homeRuntimeId !== run.homeRuntimeId || workflowId !== run.workflowId) {
throw runtimeError("run_plan_corrupt", run.runId, "run plan envelope identity does not match the run");
}
const revisionsValue = asObject(value.revisions, run.runId, "revisions");
assertExactKeys(revisionsValue, REVISION_REQUIRED, [], run.runId, "revisions");
const revisions = {
config: asString(revisionsValue.config, run.runId, "revisions.config"),
executorPolicy: asString(revisionsValue.executorPolicy, run.runId, "revisions.executorPolicy"),
toolPolicy: asString(revisionsValue.toolPolicy, run.runId, "revisions.toolPolicy"),
memory: asString(revisionsValue.memory, run.runId, "revisions.memory")
};
if (revisions.config !== run.configRevision || revisions.executorPolicy !== run.executorPolicyRevision || revisions.toolPolicy !== run.toolPolicyRevision || revisions.memory !== run.memoryRevision) {
throw runtimeError("run_plan_corrupt", run.runId, "run plan envelope revisions do not match the run");
}
const limitsValue = asObject(value.projectLimits, run.runId, "projectLimits");
assertExactKeys(limitsValue, PROJECT_LIMIT_REQUIRED, PROJECT_LIMIT_OPTIONAL, run.runId, "projectLimits");
const projectLimits = {
maxConcurrentRuns: asCount(limitsValue.maxConcurrentRuns, run.runId, "projectLimits.maxConcurrentRuns"),
...limitsValue.maxRunDurationMs !== void 0 ? { maxRunDurationMs: asDuration(limitsValue.maxRunDurationMs, run.runId, "projectLimits.maxRunDurationMs") } : {},
...limitsValue.maxAgentTimeMs !== void 0 ? { maxAgentTimeMs: asDuration(limitsValue.maxAgentTimeMs, run.runId, "projectLimits.maxAgentTimeMs") } : {},
...limitsValue.agentStepTimeoutMs !== void 0 ? { agentStepTimeoutMs: asAgentStepTimeout(limitsValue.agentStepTimeoutMs, run.runId, "projectLimits.agentStepTimeoutMs") } : {}
};
const plan = freezeKxmCompiledPlan(parseCompiledPlan(value.plan, run.runId));
return {
schema: KXM_RUN_PLAN_SCHEMA,
runId,
projectId,
homeRuntimeId,
workflowId,
revisions,
projectLimits,
plan,
gates: freezeGates(parseGates(value.gates, plan, run.runId))
};
}
function parseGates(raw, plan, runId) {
const value = asObject(raw, runId, "gates");
assertExactKeys(value, GATES_REQUIRED, [], runId, "gates");
const referenced = /* @__PURE__ */ new Set();
for (const stepId of plan.order) {
const step = plan.steps[stepId];
if (step?.kind === "gate") referenced.add(step.gate);
}
const registry = parseRegistryPin(value.registry, runId, referenced.size > 0);
const controlRoot = parseControlRoot(value.controlRoot, runId);
const definitionsValue = asObject(value.definitions, runId, "gates.definitions");
const defined = Object.keys(definitionsValue);
for (const stepId of plan.order) {
const step = plan.steps[stepId];
if (step?.kind !== "gate") continue;
if (!(step.gate in definitionsValue)) {
throw runtimeError("run_plan_corrupt", runId, `gate step ${stepId} has no pinned definition`);
}
}
for (const gateId of defined) {
if (!referenced.has(gateId)) {
throw runtimeError("run_plan_corrupt", runId, `definition ${gateId} is not referenced`);
}
}
const definitions = /* @__PURE__ */ Object.create(null);
for (const gateId of defined) {
definitions[gateId] = parseGateDefinition(definitionsValue[gateId], gateId, runId);
}
return { registry, definitions, controlRoot };
}
function parseRegistryPin(raw, runId, required2) {
if (raw === null) {
if (required2) throw runtimeError("run_plan_corrupt", runId, "gate steps require a non-null registry pin");
return null;
}
const value = asObject(raw, runId, "gates.registry");
assertExactKeys(value, REGISTRY_PIN_REQUIRED, [], runId, "gates.registry");
if (value.schema !== GATE_REGISTRY_SCHEMA) {
throw runtimeError("run_plan_corrupt", runId, "gates.registry.schema is not kxm.gate-registry.v1");
}
const hash = asString(value.hash, runId, "gates.registry.hash");
if (!/^sha256:[a-f0-9]{64}$/.test(hash)) {
throw runtimeError("run_plan_corrupt", runId, "gates.registry.hash is not a sha256 digest");
}
return { schema: GATE_REGISTRY_SCHEMA, hash };
}
function parseControlRoot(raw, runId) {
const value = asObject(raw, runId, "gates.controlRoot");
assertExactKeys(value, CONTROL_ROOT_REQUIRED, [], runId, "gates.controlRoot");
const repositoryId = asString(value.repositoryId, runId, "gates.controlRoot.repositoryId");
if (repositoryId !== "control") {
throw runtimeError("run_plan_corrupt", runId, "gates.controlRoot.repositoryId must be control");
}
return { repositoryId: "control", projectKey: asString(value.projectKey, runId, "gates.controlRoot.projectKey") };
}
function parseGateDefinition(raw, gateId, runId) {
const value = asObject(raw, runId, `gates.definitions.${gateId}`);
const kind = asString(value.kind, runId, `gates.definitions.${gateId}.kind`);
if (kind === "command") {
assertExactKeys(value, ["kind", "argv", "timeoutMs"], ["cwd"], runId, `gates.definitions.${gateId}`);
const argv = asStringArray(value.argv, runId, `gates.definitions.${gateId}.argv`);
if (argv.length < 1 || argv.length > 64) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId}.argv length is invalid`);
}
for (const [index, entry] of argv.entries()) {
if (entry.length === 0 || entry.length > 4096 || entry.includes("\0")) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId}.argv[${index}] is invalid`);
}
}
const executable = argv[0];
if (executable === "." || executable === ".." || executable.includes("\\") || !executable.startsWith("/") && executable.includes("/")) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId} argv[0] must be a bare executable or absolute POSIX path`);
}
const timeoutMs = value.timeoutMs;
if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId}.timeoutMs is invalid`);
}
if (value.cwd !== void 0 && value.cwd !== "control") {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId}.cwd is invalid`);
}
return {
kind: "command",
argv,
timeoutMs,
...value.cwd === "control" ? { cwd: "control" } : {}
};
}
if (kind === "artifacts-exist") {
assertExactKeys(value, ["kind", "paths"], [], runId, `gates.definitions.${gateId}`);
const paths = asStringArray(value.paths, runId, `gates.definitions.${gateId}.paths`);
if (paths.length < 1 || paths.length > 64) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId}.paths length is invalid`);
}
if (new Set(paths).size !== paths.length) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId}.paths are not unique`);
}
for (const path of paths) {
if (path === "." || !kxmPortablePath(path) || path.startsWith("/") || path.includes("\\")) {
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId} path is not a portable relative path`);
}
}
return { kind: "artifacts-exist", paths };
}
if (kind === "reserved") {
assertExactKeys(value, ["kind"], [], runId, `gates.definitions.${gateId}`);
return { kind: "reserved" };
}
throw runtimeError("run_plan_corrupt", runId, `gates.definitions.${gateId} kind is invalid`);
}
function freezeGates(gates) {
const definitions = /* @__PURE__ */ Object.create(null);
for (const [id, definition] of Object.entries(gates.definitions)) {
definitions[id] = deepFreeze2({ ...definition, ...definition.kind === "command" ? { argv: [...definition.argv] } : {}, ...definition.kind === "artifacts-exist" ? { paths: [...definition.paths] } : {} });
}
return deepFreeze2({
registry: gates.registry ? { ...gates.registry } : null,
definitions,
controlRoot: { ...gates.controlRoot }
});
}
function parseCompiledPlan(raw, runId) {
const value = asObject(raw, runId, "compiled plan");
assertExactKeys(value, PLAN_REQUIRED, PLAN_OPTIONAL, runId, "compiled plan");
if (value.schema !== KXM_COMPILED_WORKFLOW_SCHEMA) {
throw runtimeError("run_plan_corrupt", runId, "compiled plan schema is not kxm.compiled-workflow.v1");
}
const order = asStringArray(value.order, runId, "order");
const stepsValue = asObject(value.steps, runId, "steps");
const stepIds = Object.keys(stepsValue);
if (!sameSet(stepIds, order)) {
throw runtimeError("run_plan_corrupt", runId, "compiled plan step keys do not equal order");
}
const steps = /* @__PURE__ */ Object.create(null);
for (const stepId of order) {
steps[stepId] = parseStep(stepsValue[stepId], stepId, runId);
}
const entryStepId = asString(value.entryStepId, runId, "entryStepId");
if (!steps[entryStepId] || !order.includes(entryStepId)) {
throw runtimeError("run_plan_corrupt", runId, "entryStepId is not in compiled steps");
}
const limitsObject = asObject(value.limits, runId, "limits");
assertExactKeys(limitsObject, [], LIMIT_OPTIONAL, runId, "limits");
const limits = {
...limitsObject.maxTransitions !== void 0 ? { maxTransitions: asCount(limitsObject.maxTransitions, runId, "limits.maxTransitions") } : {},
...limitsObject.maxRunDurationMs !== void 0 ? { maxRunDurationMs: asDuration(limitsObject.maxRunDurationMs, runId, "limits.maxRunDurationMs") } : {},
...limitsObject.maxAgentTimeMs !== void 0 ? { maxAgentTimeMs: asDuration(limitsObject.maxAgentTimeMs, runId, "limits.maxAgentTimeMs") } : {},
...limitsObject.maxModelCost !== void 0 ? { maxModelCost: asCost(limitsObject.maxModelCost, runId, "limits.maxModelCost") } : {},
...limitsObject.currency !== void 0 ? { currency: asString(limitsObject.currency, runId, "limits.currency") } : {}
};
const requirePlanHash = asStringArray(value.requirePlanHash, runId, "requirePlanHash");
for (const stageId of requirePlanHash) {
if (!steps[stageId]) throw runtimeError("run_plan_corrupt", runId, `requirePlanHash references unknown step ${stageId}`);
}
const plan = {
schema: KXM_COMPILED_WORKFLOW_SCHEMA,
workflowId: asString(value.workflowId, runId, "workflowId"),
...value.sourcePath !== void 0 ? { sourcePath: asStringAllowEmpty(value.sourcePath, runId, "sourcePath") } : {},
coordinator: asString(value.coordinator, runId, "coordinator"),
limits,
transitionBudget: asCount(value.transitionBudget, runId, "transitionBudget"),
hasBackEdges: asBoolean(value.hasBackEdges, runId, "hasBackEdges"),
entryStepId,
order,
steps,
...value.reproOracle !== void 0 ? { reproOracle: parseOracle(value.reproOracle, steps, runId, "reproOracle") } : {},
...value.planHash !== void 0 ? { planHash: parseOracle(value.planHash, steps, runId, "planHash") } : {},
requirePlanHash
};
return plan;
}
function parseStep(raw, stepId, runId) {
const value = asObject(raw, runId, `step ${stepId}`);
const kind = asString(value.kind, runId, `${stepId}.kind`);
if (!SUPPORTED_KINDS.has(kind)) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} has unsupported kind ${kind}`);
}
const extraRequired = kind === "agent" || kind === "moa" ? ["agent"] : kind === "gate" ? ["gate", "expect"] : kind === "wait" ? ["signal"] : [];
assertExactKeys(value, [...STEP_REQUIRED, ...extraRequired], STEP_OPTIONAL, runId, `step ${stepId}`);
const id = asString(value.id, runId, `${stepId}.id`);
if (id !== stepId) throw runtimeError("run_plan_corrupt", runId, `step ${stepId} id does not match its key`);
const outcomes = asStringArray(value.outcomes, runId, `${stepId}.outcomes`);
if (new Set(outcomes).size !== outcomes.length) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} outcomes are not unique`);
}
const sorted = [...outcomes].sort();
if (outcomes.join("\0") !== sorted.join("\0")) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} outcomes are not sorted`);
}
const transitionsValue = asObject(value.transitions, runId, `${stepId}.transitions`);
if (!sameSet(Object.keys(transitionsValue), outcomes)) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} transition keys do not equal outcomes`);
}
const transitions = /* @__PURE__ */ Object.create(null);
for (const outcome of outcomes) {
transitions[outcome] = parseTransition2(transitionsValue[outcome], stepId, outcome, runId);
}
const repositoriesValue = asObject(value.repositories, runId, `${stepId}.repositories`);
const repositories = /* @__PURE__ */ Object.create(null);
for (const [repositoryId, access] of Object.entries(repositoriesValue)) {
if (typeof access !== "string" || !REPOSITORY_ACCESS2.has(access)) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} repository ${repositoryId} has invalid access`);
}
repositories[repositoryId] = access;
}
const base = {
id,
index: asIndex(value.index, runId, `${stepId}.index`),
...value.description !== void 0 ? { description: asStringAllowEmpty(value.description, runId, `${stepId}.description`) } : {},
...value.instructions !== void 0 ? { instructions: asStringAllowEmpty(value.instructions, runId, `${stepId}.instructions`) } : {},
maxAttempts: asCount(value.maxAttempts, runId, `${stepId}.maxAttempts`),
...value.timeoutMs !== void 0 ? { timeoutMs: asDuration(value.timeoutMs, runId, `${stepId}.timeoutMs`) } : {},
safeSpeculation: asBoolean(value.safeSpeculation, runId, `${stepId}.safeSpeculation`),
repositories,
...value.tools !== void 0 ? { tools: asJsonObject(value.tools, runId, `${stepId}.tools`) } : {},
secrets: asObjectArray(value.secrets, runId, `${stepId}.secrets`).map((entry) => ({ ...entry })),
...value.model !== void 0 ? { model: cloneJson2(value.model) } : {},
requiredEvidence: asUnknownArray(value.requiredEvidence, runId, `${stepId}.requiredEvidence`).map((entry, index) => parseEvidence(entry, stepId, index, runId)),
outcomes,
transitions,
requiresPlanHash: asBoolean(value.requiresPlanHash, runId, `${stepId}.requiresPlanHash`),
assignments: parseAssignments(value.assignments, stepId, runId),
join: parseJoin(value.join, stepId, runId)
};
if (kind === "agent" || kind === "moa") {
return { ...base, kind, agent: asString(value.agent, runId, `${stepId}.agent`) };
}
if (kind === "gate") {
const expect = asString(value.expect, runId, `${stepId}.expect`);
if (expect !== "pass" && expect !== "fail") {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} expect is invalid`);
}
return { ...base, kind, gate: asString(value.gate, runId, `${stepId}.gate`), expect };
}
if (kind === "wait") {
return { ...base, kind, signal: asString(value.signal, runId, `${stepId}.signal`) };
}
return { ...base, kind: "approval" };
}
function parseTransition2(raw, stepId, outcome, runId) {
const value = asObject(raw, runId, `${stepId}.${outcome}`);
const to = asString(value.to, runId, `${stepId}.${outcome}.to`);
const maxTransitions = value.maxTransitions !== void 0 ? asCount(value.maxTransitions, runId, `${stepId}.${outcome}.maxTransitions`) : void 0;
if (to === "step") {
assertExactKeys(value, ["to", "target", "edge"], ["maxTransitions"], runId, `${stepId}.${outcome}`);
const edge = asString(value.edge, runId, `${stepId}.${outcome}.edge`);
if (edge !== "forward" && edge !== "back") {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} transition ${outcome} edge is invalid`);
}
return {
to: "step",
target: asString(value.target, runId, `${stepId}.${outcome}.target`),
edge,
...maxTransitions !== void 0 ? { maxTransitions } : {}
};
}
if (to === "terminal") {
assertExactKeys(value, ["to", "terminalStatus"], ["maxTransitions"], runId, `${stepId}.${outcome}`);
const terminalStatus = asString(value.terminalStatus, runId, `${stepId}.${outcome}.terminalStatus`);
if (!TERMINAL.has(terminalStatus)) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} has an illegal terminal status`);
}
return {
to: "terminal",
terminalStatus,
...maxTransitions !== void 0 ? { maxTransitions } : {}
};
}
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} transition ${outcome} is not a discriminated transition`);
}
function parseAssignments(raw, stepId, runId) {
const value = asObject(raw, runId, `${stepId}.assignments`);
assertExactKeys(value, ASSIGNMENT_REQUIRED, ASSIGNMENT_OPTIONAL, runId, `${stepId}.assignments`);
const distinctBy = asStringArray(value.distinctBy, runId, `${stepId}.assignments.distinctBy`);
if (distinctBy.some((entry) => !DISTINCT_BY2.has(entry))) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} distinctBy is invalid`);
}
return {
allowedAgents: asStringArray(value.allowedAgents, runId, `${stepId}.assignments.allowedAgents`),
minimum: asCount(value.minimum, runId, `${stepId}.assignments.minimum`),
target: asCount(value.target, runId, `${stepId}.assignments.target`),
maximum: asCount(value.maximum, runId, `${stepId}.assignments.maximum`),
maxParallel: asCount(value.maxParallel, runId, `${stepId}.assignments.maxParallel`),
maxAttemptsPerAssignment: asCount(value.maxAttemptsPerAssignment, runId, `${stepId}.assignments.maxAttemptsPerAssignment`),
...value.maxWriteRepositories !== void 0 ? { maxWriteRepositories: asCount(value.maxWriteRepositories, runId, `${stepId}.assignments.maxWriteRepositories`) } : {},
distinctBy
};
}
function parseJoin(raw, stepId, runId) {
const value = asObject(raw, runId, `${stepId}.join`);
assertExactKeys(value, JOIN_REQUIRED, JOIN_OPTIONAL, runId, `${stepId}.join`);
const strategy = asString(value.strategy, runId, `${stepId}.join.strategy`);
if (!JOIN_STRATEGIES2.has(strategy)) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} join strategy is invalid`);
}
return {
strategy,
...value.minimumPassed !== void 0 ? { minimumPassed: asCount(value.minimumPassed, runId, `${stepId}.join.minimumPassed`) } : {},
...value.cancelRemaining !== void 0 ? { cancelRemaining: asBoolean(value.cancelRemaining, runId, `${stepId}.join.cancelRemaining`) } : {}
};
}
function parseEvidence(raw, stepId, index, runId) {
const value = asObject(raw, runId, `${stepId}.requiredEvidence[${index}]`);
assertExactKeys(value, EVIDENCE_REQUIRED, EVIDENCE_OPTIONAL, runId, `${stepId}.requiredEvidence[${index}]`);
const kind = asString(value.kind, runId, `${stepId}.requiredEvidence[${index}].kind`);
if (!EVIDENCE_KINDS2.has(kind)) {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} evidence kind is invalid`);
}
return {
key: asString(value.key, runId, `${stepId}.requiredEvidence[${index}].key`),
kind,
minimum: asCount(value.minimum, runId, `${stepId}.requiredEvidence[${index}].minimum`),
reusableAcrossAttempts: asBoolean(value.reusableAcrossAttempts, runId, `${stepId}.requiredEvidence[${index}].reusableAcrossAttempts`),
...value.producerPolicy !== void 0 ? { producerPolicy: parseProducerPolicy(value.producerPolicy, stepId, runId) } : {}
};
}
function parseProducerPolicy(raw, stepId, runId) {
const value = asObject(raw, runId, `${stepId}.producerPolicy`);
assertExactKeys(value, ["minimumProducers", "eligibleAgents", "acceptedStatuses"], ["degradation"], runId, `${stepId}.producerPolicy`);
const accepted = value.acceptedStatuses;
if (!Array.isArray(accepted) || accepted.length !== 1 || accepted[0] !== "passed") {
throw runtimeError("run_plan_corrupt", runId, `step ${stepId} producerPolicy.acceptedStatuses is invalid`);
}
let degradation;
if (value.degradation !== void 0) {
const nested = asObject(value.degradation, runId, `${stepId}.producerPolicy.degradation`);
assertExactKeys(nested, ["minimumProducers"], [], runId, `${stepId}.producerPolicy.degradation`);
degradation = { minimumProducers: asCount(nested.minimumProducers, runId, `${stepId}.producerPolicy.degradation.minimumProducers`) };
}
return {
minimumProducers: asCount(value.minimumProducers, runId, `${stepId}.producerPolicy.minimumProducers`),
eligibleAgents: asStringArray(value.eligibleAgents, runId, `${stepId}.producerPolicy.eligibleAgents`),
acceptedStatuses: ["passed"],
...degradation ? { degradation } : {}
};
}
function parseOracle(raw, steps, runId, label) {
const value = asObject(raw, runId, label);
assertExactKeys(value, ["stageId", "evidenceKey"], [], runId, label);
const stageId = asString(value.stageId, runId, `${label}.stageId`);
const evidenceKey = asString(value.evidenceKey, runId, `${label}.evidenceKey`);
const step = steps[stageId];
if (!step) throw runtimeError("run_plan_corrupt", runId, `${label} references unknown stage ${stageId}`);
if (!step.requiredEvidence.some((item) => item.key === evidenceKey)) {
throw runtimeError("run_plan_corrupt", runId, `${label} references undeclared evidence ${evidenceKey}`);
}
return { stageId, evidenceKey };
}
function asObject(value, runId, label) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not an object`);
}
return value;
}
function assertExactKeys(value, required2, optional, runId, label) {
const allowed = /* @__PURE__ */ new Set([...required2, ...optional]);
for (const key of required2) {
if (!(key in value)) throw runtimeError("run_plan_corrupt", runId, `${label} is missing ${key}`);
}
for (const key of Object.keys(value)) {
if (!allowed.has(key)) throw runtimeError("run_plan_corrupt", runId, `${label} has unexpected key ${key}`);
}
}
function asString(value, runId, label) {
if (typeof value !== "string" || value.length === 0) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not a non-empty string`);
}
return value;
}
function asStringAllowEmpty(value, runId, label) {
if (typeof value !== "string") throw runtimeError("run_plan_corrupt", runId, `${label} is not a string`);
return value;
}
function asBoolean(value, runId, label) {
if (typeof value !== "boolean") throw runtimeError("run_plan_corrupt", runId, `${label} is not a boolean`);
return value;
}
function asCount(value, runId, label) {
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not a positive integer`);
}
return value;
}
function asDuration(value, runId, label) {
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not a duration integer`);
}
return value;
}
function asAgentStepTimeout(value, runId, label) {
if (typeof value !== "number" || !Number.isInteger(value) || value < 6e4) {
throw runtimeError("run_plan_corrupt", runId, `${label} is below 60000`);
}
return value;
}
function asCost(value, runId, label) {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not a positive cost`);
}
return value;
}
function asIndex(value, runId, label) {
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not a non-negative integer`);
}
return value;
}
function asStringArray(value, runId, label) {
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not a string array`);
}
return [...value];
}
function asUnknownArray(value, runId, label) {
if (!Array.isArray(value)) throw runtimeError("run_plan_corrupt", runId, `${label} is not an array`);
return value;
}
function asObjectArray(value, runId, label) {
if (!Array.isArray(value)) throw runtimeError("run_plan_corrupt", runId, `${label} is not an array`);
return value.map((entry, index) => asJsonObject(entry, runId, `${label}[${index}]`));
}
function asJsonObject(value, runId, label) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw runtimeError("run_plan_corrupt", runId, `${label} is not an object`);
}
return cloneJson2(value);
}
function cloneJson2(value) {
return JSON.parse(JSON.stringify(value));
}
function sameSet(left, right) {
if (left.length !== right.length) return false;
const set = new Set(right);
return left.every((entry) => set.has(entry));
}
function deepFreeze2(value) {
if (value === null || typeof value !== "object") return value;
if (Array.isArray(value)) {
for (const entry of value) deepFreeze2(entry);
} else {
for (const entry of Object.values(value)) deepFreeze2(entry);
}
return Object.freeze(value);
}
// plugins/kxm/src/gate-hash.ts
function gateDefinitionHash(id, definition) {
return kxmSha256(kxmCanonicalJson({ id, ...definition }));
}
function gateRegistryHash(registryValue) {
return kxmSha256(kxmCanonicalJson(registryValue));
}
// plugins/kxm/src/engine-evidence.ts
function verifyKxmGateEvidence(store, run, envelope2, events, state) {
const attempts = store.gateAttemptsForRun(run.runId);
const observations = store.gateObservationsForRun(run.runId);
const evidence = store.gateEvidenceForRun(run.runId);
const counts = store.gateRowCounts(run.runId);
if (counts.attempts !== attempts.length || counts.observations !== observations.length || counts.evidence !== evidence.length) {
throw runtimeError("gate_evidence_orphan", run.runId, "gate row counts do not match loaded attempt/observation/evidence tuples");
}
const attemptById = new Map(attempts.map((row) => [row.attemptId, row]));
const observationByAttempt = new Map(observations.map((row) => [row.attemptId, row]));
const evidenceByAttempt = new Map(evidence.map((row) => [row.attemptId, row]));
const intentEvents = events.filter((event) => event.eventType === "effect.intent_recorded");
const observedEvents = events.filter((event) => event.eventType === "effect.observed" || event.eventType === "effect.blocked_uncertain");
const settledEvents = events.filter((event) => event.eventType === "effect.settled");
for (const event of intentEvents) {
const attemptId = stringField(event, "attemptId");
const row = attemptById.get(attemptId);
if (!row) throw runtimeError("gate_attempt_pin_mismatch", run.runId, `effect.intent_recorded ${event.eventId} has no gate_attempts row`);
assertAttemptMatchesEvent(run, envelope2, state, event, row);
}
for (const event of observedEvents) {
const attemptId = stringField(event, "attemptId");
const receipt = event.payload.receipt;
const observationId = typeof receipt?.id === "string" ? receipt.id : void 0;
const row = observationByAttempt.get(attemptId);
if (!row || row.observationId !== observationId) {
throw runtimeError("gate_observation_missing", run.runId, `${event.eventType} has no matching observation row`);
}
if (row.recordedEventId !== event.eventId) {
throw runtimeError("gate_observation_missing", run.runId, "observation recorded_event_id does not match the event");
}
if (gateRowContentHash("gate_observations", row) !== row.contentHash) {
throw runtimeError("gate_evidence_hash_mismatch", run.runId, "observation contentHash does not recompute");
}
if (typeof receipt?.hash === "string" && receipt.hash !== row.contentHash) {
throw runtimeError("gate_evidence_hash_mismatch", run.runId, "observation receipt.hash does not match the row");
}
const attempt = attemptById.get(attemptId);
if (!attempt) throw runtimeError("gate_attempt_pin_mismatch", run.runId, "observation has no gate attempt");
assertShared(run, row, attempt);
assertClosedGateObservation(attempt.gateKind, row, row.observationId);
if (event.eventType === "effect.observed" && row.completeness !== "complete" && row.completeness !== "no-start") {
throw runtimeError("gate_observation_missing", run.runId, "effect.observed requires complete or no-start completeness");
}
if (event.eventType === "effect.blocked_uncertain" && row.completeness !== "incomplete") {
throw runtimeError("gate_observation_missing", run.runId, "blocked_uncertain requires incomplete completeness");
}
}
for (const event of settledEvents) {
const attemptId = stringField(event, "attemptId");
const refs = event.payload.evidenceRefs;
const evaluated = Array.isArray(refs) && refs.length > 0;
if (evaluated) {
const row = evidenceByAttempt.get(attemptId);
const ref = refs[0];
if (!row || row.evidenceId !== ref.id) {
throw runtimeError("gate_evidence_missing", run.runId, "effect.settled has no matching evidence row");
}
if (row.settledEventId !== event.eventId) {
throw runtimeError("gate_evidence_missing", run.runId, "evidence settled_event_id does not match the event");
}
if (gateRowContentHash("gate_evidence", row) !== row.contentHash || typeof ref.hash === "string" && ref.hash !== row.contentHash) {
throw runtimeError("gate_evidence_hash_mismatch", run.runId, "evidence hash does not recompute");
}
if (row.outcome !== event.payload.outcome) {
throw runtimeError("gate_evidence_hash_mismatch", run.runId, "evidence outcome does not match the settled payload");
}
const attempt = attemptById.get(attemptId);
if (!attempt) throw runtimeError("gate_attempt_pin_mismatch", run.runId, "evidence has no gate attempt");
assertShared(run, row, attempt);
if (row.expect !== attempt.expect) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "evidence expect does not match the gate attempt");
}
const observation = observationByAttempt.get(attemptId);
if (!observation || observation.observationId !== row.observationId) {
throw runtimeError("gate_observation_missing", run.runId, "evidence observation_id does not match the attempt observation");
}
const recomputed = computeGateEvidenceOutcome(attempt.gateKind, attempt.expect, observation);
if (row.outcome !== recomputed || event.payload.outcome !== recomputed) {
throw runtimeError("gate_evidence_hash_mismatch", run.runId, "evidence outcome does not match the observation and expect");
}
const step = envelope2.plan.steps[row.stepId];
const required2 = step?.requiredEvidence.filter((item) => item.kind === "gate") ?? [];
const expectedKey = required2.length === 1 ? required2[0].key : null;
if (row.evidenceKey !== expectedKey) {
throw runtimeError("gate_evidence_unexpected", run.runId, "evidence_key does not match the declared requiredEvidence key");
}
} else {
if (evidenceByAttempt.has(attemptId)) {
throw runtimeError("gate_evidence_unexpected", run.runId, "proof-only settlement must not have a gate_evidence row");
}
const observation = observationByAttempt.get(attemptId);
const receipt = event.payload.receipt;
if (!observation || observation.observationId !== receipt?.id || observation.contentHash !== receipt?.hash) {
throw runtimeError("gate_observation_missing", run.runId, "proof-only settlement does not bind the observation");
}
}
}
const namedAttemptIds = new Set(intentEvents.map((event) => stringField(event, "attemptId")));
for (const row of attempts) {
if (!namedAttemptIds.has(row.attemptId)) {
throw runtimeError("gate_evidence_orphan", run.runId, `gate_attempts row ${row.attemptId} is not named by effect.intent_recorded`);
}
if (row.runId !== run.runId) throw runtimeError("gate_evidence_orphan", run.runId, "gate attempt belongs to a foreign run");
if (gateRowContentHash("gate_attempts", row) !== row.contentHash) {
throw runtimeError("gate_evidence_hash_mismatch", run.runId, "gate attempt contentHash does not recompute");
}
}
for (const row of observations) {
if (!attemptById.has(row.attemptId)) {
throw runtimeError("gate_evidence_orphan", run.runId, `observation ${row.observationId} is owned by this run but names a foreign attempt`);
}
const event = events.find((item) => item.eventId === row.recordedEventId);
if (!event || event.eventType !== "effect.observed" && event.eventType !== "effect.blocked_uncertain") {
throw runtimeError("gate_evidence_orphan", run.runId, `observation ${row.observationId} is not named by an observation event`);
}
if (stringField(event, "attemptId") !== row.attemptId) {
throw runtimeError("gate_evidence_orphan", run.runId, `observation ${row.observationId} is not named by this attempt's observation event`);
}
const attempt = attemptById.get(row.attemptId);
assertShared(run, row, attempt);
assertClosedGateObservation(attempt.gateKind, row, row.observationId);
}
for (const row of evidence) {
if (!attemptById.has(row.attemptId)) {
throw runtimeError("gate_evidence_orphan", run.runId, `evidence ${row.evidenceId} is owned by this run but names a foreign attempt`);
}
const event = events.find((item) => item.eventId === row.settledEventId);
if (!event || event.eventType !== "effect.settled") {
throw runtimeError("gate_evidence_orphan", run.runId, `evidence ${row.evidenceId} is not named by effect.settled`);
}
if (stringField(event, "attemptId") !== row.attemptId) {
throw runtimeError("gate_evidence_orphan", run.runId, `evidence ${row.evidenceId} is not named by this attempt's settled event`);
}
const refs = event.payload.evidenceRefs;
if (!Array.isArray(refs) || refs.length !== 1 || refs[0].id !== row.evidenceId) {
throw runtimeError("gate_evidence_orphan", run.runId, "evidence row is not the payload evidenceRef");
}
const attempt = attemptById.get(row.attemptId);
assertShared(run, row, attempt);
if (row.expect !== attempt.expect) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "evidence expect does not match the gate attempt");
}
}
if (attempts.length !== intentEvents.length) {
throw runtimeError("gate_evidence_orphan", run.runId, "gate attempt count does not match intent events");
}
if (observations.length !== observedEvents.length) {
throw runtimeError("gate_observation_missing", run.runId, "observation count does not match observation events");
}
const lastEffect = lastEffectByAttempt(events);
for (const [attemptId, last] of lastEffect) {
const evidenceRow = evidenceByAttempt.get(attemptId);
if (last === "effect.settled") {
const settled = settledEvents.filter((event) => stringField(event, "attemptId") === attemptId).at(-1);
const evaluated = Array.isArray(settled?.payload.evidenceRefs) && settled.payload.evidenceRefs.length > 0;
if (evaluated && !evidenceRow) throw runtimeError("gate_evidence_missing", run.runId, "evaluated settlement is missing evidence");
if (!evaluated && evidenceRow) throw runtimeError("gate_evidence_unexpected", run.runId, "proof-only settlement has evidence");
const capability = store.capabilityByAttempt(attemptId);
if (evaluated && capability?.state === "issued") {
throw runtimeError("gate_evidence_unexpected", run.runId, "settled attempt still has issued capability");
}
} else if (evidenceRow) {
throw runtimeError("gate_evidence_unexpected", run.runId, "non-settled attempt has evidence");
}
}
void kxmCanonicalJson;
}
function lastEffectByAttempt(events) {
const last = /* @__PURE__ */ new Map();
for (const event of events) {
if (!event.eventType.startsWith("effect.")) continue;
const attemptId = event.payload.attemptId;
if (typeof attemptId === "string") last.set(attemptId, event.eventType);
}
return last;
}
function assertAttemptMatchesEvent(run, envelope2, state, event, row) {
const effectId = event.payload.effect?.id;
if (row.effectId !== effectId || row.intentEventId !== event.eventId) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "intent event does not match the gate attempt");
}
if (row.runId !== run.runId || row.projectId !== run.projectId || row.homeRuntimeId !== run.homeRuntimeId) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "gate attempt owner does not match the run");
}
if (row.stepId !== event.payload.stepId || row.stepAttempt !== event.payload.stepAttempt || row.assignmentId !== event.payload.assignmentId || row.attemptId !== event.payload.attemptId) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "gate attempt identity does not match the intent payload");
}
const step = envelope2.plan.steps[row.stepId];
if (!step || step.kind !== "gate") {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "gate attempt step is not a gate");
}
if (row.gateId !== step.gate || row.expect !== step.expect) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "gate attempt gate/expect do not match the plan");
}
const definition = envelope2.gates.definitions[step.gate];
if (!definition || definition.kind !== row.gateKind) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "gate attempt kind does not match the pinned definition");
}
const expectedDefinitionHash = gateDefinitionHash(step.gate, definition);
if (row.gateDefinitionHash !== expectedDefinitionHash) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "gate_definition_hash does not match the pinned definition");
}
if (!envelope2.gates.registry || row.registryHash !== envelope2.gates.registry.hash) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "registry_hash does not match the pinned registry");
}
const planRowHash = envelope2 && state.runPlanHash;
if (row.runPlanHash !== planRowHash) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "run_plan_hash does not match the pinned plan");
}
if (row.controlProjectKey !== envelope2.gates.controlRoot.projectKey) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "control_project_key does not match the envelope");
}
}
function assertShared(run, row, attempt) {
if (row.runId !== attempt.runId || row.projectId !== attempt.projectId || row.homeRuntimeId !== attempt.homeRuntimeId || row.stepId !== attempt.stepId || row.stepAttempt !== attempt.stepAttempt || row.assignmentId !== attempt.assignmentId || row.effectId !== attempt.effectId) {
throw runtimeError("gate_attempt_pin_mismatch", run.runId, "row identity does not match the gate attempt");
}
}
function stringField(event, field) {
const value = event.payload[field];
if (typeof value !== "string" || value.length === 0) {
throw runtimeError("gate_attempt_pin_mismatch", event.runId, `${event.eventType} is missing ${field}`);
}
return value;
}
// plugins/kxm/src/runtime-owner.ts
import { randomUUID as randomUUID2 } from "node:crypto";
var owners = /* @__PURE__ */ new Map();
function record(storePath) {
const existing = owners.get(storePath);
if (existing) return existing;
const created = {
handles: 0,
admitted: /* @__PURE__ */ new Map(),
queue: [],
attempts: /* @__PURE__ */ new Map()
};
owners.set(storePath, created);
return created;
}
function maybeDelete(storePath, owner) {
if (owner.handles === 0 && owner.admitted.size === 0 && owner.queue.length === 0 && owner.attempts.size === 0) {
owners.delete(storePath);
}
}
function activePolicy(owner) {
return owner.scheduler ?? owner.implicit;
}
function clearImplicitIfIdle(owner) {
if (owner.admitted.size === 0 && owner.queue.length === 0) {
delete owner.implicit;
}
}
function registerKxmRuntimeHandle(storePath) {
record(storePath).handles += 1;
}
function unregisterKxmRuntimeHandle(storePath) {
const owner = owners.get(storePath);
if (!owner) return;
owner.handles = Math.max(0, owner.handles - 1);
maybeDelete(storePath, owner);
}
function registerKxmAttemptController(storePath, runId, attempt) {
const owner = record(storePath);
let runAttempts = owner.attempts.get(runId);
if (!runAttempts) {
runAttempts = /* @__PURE__ */ new Map();
owner.attempts.set(runId, runAttempts);
}
if (runAttempts.has(attempt.attemptId)) {
throw runtimeError("attempt_controller_duplicate", attempt.attemptId, `attempt ${attempt.attemptId} is already registered`);
}
runAttempts.set(attempt.attemptId, attempt);
}
function kxmAttemptController(storePath, runId, attemptId) {
return owners.get(storePath)?.attempts.get(runId)?.get(attemptId);
}
function kxmAttemptControllers(storePath, runId) {
const runAttempts = owners.get(storePath)?.attempts.get(runId);
if (!runAttempts) return [];
return [...runAttempts.values()];
}
function unregisterKxmAttemptController(storePath, runId, attemptId) {
const owner = owners.get(storePath);
if (!owner) return;
const runAttempts = owner.attempts.get(runId);
if (!runAttempts) return;
if (!runAttempts.has(attemptId)) return;
runAttempts.delete(attemptId);
if (runAttempts.size === 0) owner.attempts.delete(runId);
maybeDelete(storePath, owner);
}
function bindKxmSchedulerPolicy(storePath, bound, configRevision) {
const owner = record(storePath);
const current = activePolicy(owner);
if (current && (current.configRevision !== configRevision || current.bound !== bound)) {
if (owner.admitted.size > 0 || owner.queue.length > 0) {
throw runtimeError("scheduler_policy_conflict", storePath, "queued or admitted work still uses the previous scheduler policy");
}
}
owner.scheduler = { bound, configRevision };
delete owner.implicit;
}
function kxmSchedulerPolicy(storePath) {
return owners.get(storePath)?.scheduler;
}
function admitKxmRun(storePath, runId, envelopeRevision, envelopeBound) {
const owner = record(storePath);
if (owner.admitted.has(runId)) {
throw runtimeError("run_busy", runId, `run ${runId} is already admitted`);
}
if (owner.queue.some((item) => item.runId === runId)) {
throw runtimeError("run_busy", runId, `run ${runId} is already queued`);
}
const policy = activePolicy(owner);
if (policy) {
if (policy.configRevision !== envelopeRevision) {
throw runtimeError("scheduler_policy_conflict", runId, "run envelope revision does not match the active admission policy");
}
if (policy.bound !== envelopeBound) {
throw runtimeError("scheduler_policy_conflict", runId, "run envelope bound does not match the active admission policy");
}
} else {
owner.implicit = { bound: envelopeBound, configRevision: envelopeRevision };
}
const bound = activePolicy(owner).bound;
if (owner.admitted.size >= bound) {
throw runtimeError("run_admission_exceeded", runId, `project already has ${bound} admitted runs`);
}
const token = randomUUID2();
owner.admitted.set(runId, { token, configRevision: envelopeRevision });
return token;
}
function releaseKxmRun(storePath, runId, token) {
const owner = owners.get(storePath);
if (!owner) return;
const current = owner.admitted.get(runId);
if (!current || current.token !== token) return;
if (current.gateHold) return;
owner.admitted.delete(runId);
pump(storePath, owner);
clearImplicitIfIdle(owner);
maybeDelete(storePath, owner);
}
function armKxmGateHold(storePath, runId, token, attemptId, stop) {
const owner = record(storePath);
const current = owner.admitted.get(runId);
if (!current || current.token !== token) {
throw runtimeError("run_events_illegal", runId, "gate hold requires the exact admitted token");
}
if (current.gateHold) {
throw runtimeError("run_events_illegal", runId, "admission already has a gate hold");
}
current.gateHold = { attemptId, token, state: "active", stop };
}
function markKxmGateHoldUnsettled(storePath, runId, token, attemptId) {
const owner = owners.get(storePath);
const current = owner?.admitted.get(runId);
if (!current || current.token !== token) {
throw runtimeError("run_events_illegal", runId, "unsettled hold requires the exact admitted token");
}
const hold = current.gateHold;
if (!hold || hold.attemptId !== attemptId || hold.token !== token) {
throw runtimeError("run_events_illegal", runId, "unsettled hold does not match the armed attempt");
}
hold.state = "unsettled";
}
function finishKxmOwnedGate(storePath, runId, token, attemptId) {
const owner = owners.get(storePath);
const current = owner?.admitted.get(runId);
if (!current || current.token !== token) {
throw runtimeError("run_events_illegal", runId, "owned gate finish requires the exact admitted token");
}
const hold = current.gateHold;
if (!hold || hold.attemptId !== attemptId || hold.token !== token) {
throw runtimeError("run_events_illegal", runId, "owned gate finish does not match the armed attempt");
}
if (hold.state === "unsettled") {
throw runtimeError("run_events_illegal", runId, "unsettled gate hold cannot be finished");
}
delete current.gateHold;
}
function dropKxmGateStopHook(storePath, runId, attemptId) {
const hold = owners.get(storePath)?.admitted.get(runId)?.gateHold;
if (!hold || hold.attemptId !== attemptId) return;
delete hold.stop;
}
function resolveKxmGateHold(storePath, runId, attemptId) {
const owner = owners.get(storePath);
if (!owner) return;
const current = owner.admitted.get(runId);
if (!current) return;
const hold = current.gateHold;
if (!hold || hold.attemptId !== attemptId) return;
try {
hold.stop?.();
} catch {
}
delete current.gateHold;
owner.admitted.delete(runId);
pump(storePath, owner);
clearImplicitIfIdle(owner);
maybeDelete(storePath, owner);
}
function kxmGateHold(storePath, runId) {
const hold = owners.get(storePath)?.admitted.get(runId)?.gateHold;
if (!hold) return void 0;
return { attemptId: hold.attemptId, token: hold.token, state: hold.state };
}
function kxmAdmittedToken(storePath, runId) {
return owners.get(storePath)?.admitted.get(runId)?.token;
}
function attachKxmDriveSession(storePath, runId, token, session) {
const owner = record(storePath);
const current = owner.admitted.get(runId);
if (!current || current.token !== token) {
throw runtimeError("run_events_illegal", runId, "drive session requires the exact admitted token");
}
if (current.driveSession) {
throw runtimeError("run_busy", runId, `run ${runId} already has a drive session`);
}
current.driveSession = session;
}
function clearKxmDriveSession(storePath, runId, token) {
const owner = owners.get(storePath);
const current = owner?.admitted.get(runId);
if (!current || current.token !== token) return;
delete current.driveSession;
}
function kxmDriveSession(storePath, runId) {
return owners.get(storePath)?.admitted.get(runId)?.driveSession;
}
function kxmOpenDriveSessions(storePath) {
const owner = owners.get(storePath);
if (!owner) return [];
const sessions = [];
for (const current of owner.admitted.values()) {
if (current.driveSession) sessions.push(current.driveSession);
}
return sessions;
}
function enqueueKxmScheduledRun(storePath, runId, configRevision, bound, start) {
const owner = record(storePath);
if (owner.admitted.has(runId) || owner.queue.some((item) => item.runId === runId)) {
return Promise.reject(runtimeError("run_busy", runId, `run ${runId} is already admitted or queued`));
}
return new Promise((resolve15, reject) => {
owner.queue.push({
runId,
configRevision,
bound,
start: (token) => start(token).then(resolve15, reject),
fail: (error) => reject(error)
});
pump(storePath, owner);
});
}
function pump(storePath, owner) {
const bound = activePolicy(owner)?.bound ?? 1;
while (owner.admitted.size < bound && owner.queue.length > 0) {
const next = owner.queue.shift();
if (!next) break;
let token;
try {
token = admitKxmRun(storePath, next.runId, next.configRevision, next.bound);
} catch (error) {
next.fail(error);
continue;
}
void next.start(token).finally(() => {
releaseKxmRun(storePath, next.runId, token);
});
}
}
// plugins/kxm/src/runtime-service.ts
function compareCodeUnits6(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
function sha256Of(input) {
return `sha256:${createHash9("sha256").update(input, "utf8").digest("hex")}`;
}
function objectValue3(value) {
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
}
function kxmExecutorPolicyRevision(bundle) {
const executors = /* @__PURE__ */ new Set();
const defaultExecutor = bundle.project.value.defaultExecutor;
if (typeof defaultExecutor === "string") executors.add(defaultExecutor);
for (const agent of bundle.agents.values()) {
const executor = agent.value.executor;
if (typeof executor === "string") executors.add(executor);
}
return sha256Of(kxmCanonicalJson([...executors].sort()));
}
function kxmToolPolicyRevision(bundle) {
const policies = [];
for (const agent of [...bundle.agents.values()].sort((left, right) => String(left.id).localeCompare(String(right.id)))) {
policies.push({ agent: agent.id ?? "unknown", tools: objectValue3(agent.value.tools) ?? null });
}
for (const workflow of [...bundle.workflows.values()].sort((left, right) => String(left.id).localeCompare(String(right.id)))) {
const steps = Array.isArray(workflow.value.steps) ? workflow.value.steps : [];
for (const step of steps) {
const record2 = objectValue3(step);
if (record2?.tools !== void 0) {
policies.push({ workflow: workflow.id ?? "unknown", step: record2.id ?? null, tools: objectValue3(record2.tools) ?? null });
}
}
}
return sha256Of(kxmCanonicalJson({ policies, gateRegistry: bundle.gateRegistry?.value ?? null }));
}
function collectMemoryFiles(dir, baseDir, ignoreSubdirs = /* @__PURE__ */ new Set()) {
if (!existsSync8(dir)) return [];
const entries = readdirSync4(dir, { withFileTypes: true });
const results = [];
for (const entry of entries) {
const fullPath = join8(dir, entry.name);
if (entry.isDirectory()) {
if (ignoreSubdirs.has(entry.name)) continue;
results.push(...collectMemoryFiles(fullPath, baseDir, ignoreSubdirs));
} else if (entry.isFile()) {
const relPath = fullPath.slice(baseDir.length + 1).replace(/\\/g, "/");
results.push({ relPath, fullPath });
}
}
return results;
}
function computeKxmMemoryRevision(bundle, options = {}) {
const hash = createHash9("sha256");
const memoryDir = options.memoryDir ?? join8(bundle.projectRoot, ".kxm", "memory");
const memoryFiles = collectMemoryFiles(memoryDir, memoryDir, /* @__PURE__ */ new Set(["candidates"])).sort((left, right) => compareCodeUnits6(left.relPath, right.relPath));
for (const file of memoryFiles) {
hash.update(`memory:${file.relPath}\0`, "utf8");
hash.update(readFileSync5(file.fullPath));
hash.update("\0", "utf8");
}
const skillsDir = options.skillsDir ?? join8(bundle.projectRoot, ".kxm", "skills");
const promotedSkillsDir = join8(skillsDir, "promoted");
const skillFiles = collectMemoryFiles(promotedSkillsDir, promotedSkillsDir).sort((left, right) => compareCodeUnits6(left.relPath, right.relPath));
for (const file of skillFiles) {
hash.update(`skill:${file.relPath}\0`, "utf8");
hash.update(readFileSync5(file.fullPath));
hash.update("\0", "utf8");
}
if (options.promotedState && options.promotedState.length > 0) {
const currentItems = options.promotedState.filter((item) => !item.status || item.status === "current").slice().sort((left, right) => compareCodeUnits6(left.id, right.id));
for (const item of currentItems) {
hash.update(`state:${item.id}\0`, "utf8");
hash.update(kxmCanonicalJson(item), "utf8");
hash.update("\0", "utf8");
}
}
return `ctxrev_${hash.digest("hex")}`;
}
function checkMemoryRevisionDrift(pinnedRevision, bundle, options) {
const currentRevision = computeKxmMemoryRevision(bundle, options);
return {
drifted: currentRevision !== pinnedRevision,
currentRevision,
pinnedRevision
};
}
function kxmPolicyRevisions(bundle, options) {
return {
configRevision: bundle.configRevision,
memoryRevision: computeKxmMemoryRevision(bundle, options),
executorPolicyRevision: kxmExecutorPolicyRevision(bundle),
toolPolicyRevision: kxmToolPolicyRevision(bundle)
};
}
function kxmDeclaredRepositoryIds(bundle) {
return [...bundle.repositories.keys()].sort();
}
function kxmDeclaredExecutorIds(bundle) {
return [...new Set([
typeof bundle.project.value.defaultExecutor === "string" ? bundle.project.value.defaultExecutor : void 0,
...[...bundle.agents.values()].map((agent) => agent.value.executor).filter((value) => typeof value === "string")
].filter((value) => value !== void 0))].sort();
}
var KXM_DEFAULT_AGENT_STEP_TIMEOUT_MS = 36e5;
var KXM_MIN_AGENT_STEP_TIMEOUT_MS = 6e4;
function kxmProjectAdmissionLimits(bundle) {
const limits = objectValue3(bundle.project.value.limits);
const maxConcurrentRuns = typeof limits?.maxConcurrentRuns === "number" && Number.isInteger(limits.maxConcurrentRuns) && limits.maxConcurrentRuns >= 1 ? limits.maxConcurrentRuns : 1;
const declared = limits?.agentStepTimeoutMs;
const agentStepTimeoutMs = typeof declared === "number" && Number.isInteger(declared) && declared >= KXM_MIN_AGENT_STEP_TIMEOUT_MS ? declared : KXM_DEFAULT_AGENT_STEP_TIMEOUT_MS;
return {
maxConcurrentRuns,
...typeof limits?.maxRunDurationMs === "number" ? { maxRunDurationMs: limits.maxRunDurationMs } : {},
...typeof limits?.maxAgentTimeMs === "number" ? { maxAgentTimeMs: limits.maxAgentTimeMs } : {},
agentStepTimeoutMs
};
}
var closedRuntimeContexts = /* @__PURE__ */ new WeakSet();
var runtimeCloseHooks = /* @__PURE__ */ new WeakMap();
function isKxmRuntimeContextClosed(context) {
return closedRuntimeContexts.has(context);
}
function registerKxmRuntimeCloseHook(context, hook) {
if (closedRuntimeContexts.has(context)) {
hook();
return () => void 0;
}
let hooks = runtimeCloseHooks.get(context);
if (!hooks) {
hooks = /* @__PURE__ */ new Set();
runtimeCloseHooks.set(context, hooks);
}
hooks.add(hook);
return () => {
hooks.delete(hook);
};
}
function openKxmRuntimeContext(projectRoot, options) {
const paths = kxmRuntimePaths(options.stateRoot !== void 0 ? { stateRoot: options.stateRoot } : {});
const registry = new KxmRuntimeRegistry(paths.registryDb);
try {
const bundle = loadKxmProject(projectRoot, options);
const projectId = String(bundle.project.value.id);
const registration = registry.registerProject({
projectId,
projectRoot: bundle.projectRoot,
homeRuntimeId: options.homeRuntimeId,
configRevision: bundle.configRevision,
now: options.now ?? (/* @__PURE__ */ new Date()).toISOString(),
...options.logger ? { logger: options.logger } : {}
});
const eventStore = new KxmRunEventStore(join8(paths.projectsDir, registration.projectKey, "run-events.db"));
registerKxmRuntimeHandle(eventStore.path);
return {
registry,
projectRoot: bundle.projectRoot,
projectId: registration.projectId,
homeRuntimeId: registration.homeRuntimeId,
eventStore,
configRevision: bundle.configRevision,
...options.budgetClock ? { budgetClock: options.budgetClock } : {},
...options.logger ? { logger: options.logger } : {}
};
} catch (error) {
registry.close();
throw error;
}
}
function closeKxmRuntimeContext(context) {
if (closedRuntimeContexts.has(context)) return;
closedRuntimeContexts.add(context);
const hooks = runtimeCloseHooks.get(context);
runtimeCloseHooks.delete(context);
if (hooks) {
for (const hook of hooks) {
try {
hook();
} catch {
}
}
}
unregisterKxmRuntimeHandle(context.eventStore.path);
context.eventStore.close();
context.registry.close();
}
var RUNTIME_EPOCH_NS = process.hrtime.bigint();
function kxmMonotonicNs() {
return (process.hrtime.bigint() - RUNTIME_EPOCH_NS).toString();
}
function kxmIncrementMonotonicNs(value) {
return (BigInt(value) + 1n).toString();
}
function kxmEventBase(context, run, now, monotonicNs, commandId) {
return {
schema: KXM_RUN_EVENT_SCHEMA,
projectId: context.projectId,
runId: run.runId,
homeRuntimeId: run.homeRuntimeId,
occurredAt: now,
recordedAt: now,
monotonicNs,
configRevision: run.configRevision,
memoryRevision: run.memoryRevision,
executorPolicyRevision: run.executorPolicyRevision,
toolPolicyRevision: run.toolPolicyRevision,
...commandId !== void 0 ? { commandId } : {}
};
}
function acceptKxmRun(context, bundle, request, options = {}) {
const commandId = request.commandId ?? newKxmCommandId();
const now = options.now ?? (/* @__PURE__ */ new Date()).toISOString();
const monotonicNs = options.monotonicNs ?? kxmMonotonicNs();
const workflow = lookupKxmResource(bundle.workflows.values(), request.workflowId, "workflow");
if (!workflow) {
throw runtimeError("run_workflow_unknown", ".kxm/workflows", `workflow ${request.workflowId} does not exist in this project`);
}
const revisions = kxmPolicyRevisions(bundle, options);
const memoryRevision = options.memoryRevision ?? revisions.memoryRevision;
const promptSha256 = `sha256:${createHash9("sha256").update(request.prompt, "utf8").digest("hex")}`;
return context.eventStore.transaction(() => {
const prior = context.eventStore.command(commandId);
if (prior) {
if (prior.kind !== "run.accept") {
throw runtimeError("run_command_conflict", commandId, `command ${commandId} was already used for ${prior.kind}`);
}
const run2 = context.eventStore.run(prior.runId);
if (!run2) throw runtimeError("run_command_corrupt", commandId, "idempotent command references a missing run");
if (run2.workflowId !== request.workflowId || run2.promptSha256 !== promptSha256) {
throw runtimeError("run_command_conflict", commandId, "idempotent retry must repeat the same workflow and prompt");
}
const events = context.eventStore.events(run2.runId, 0, 1);
if (events.length === 0) throw runtimeError("run_command_corrupt", commandId, "idempotent command references a run with no creation event");
return { accepted: true, idempotent: true, run: run2, event: events[0] };
}
const runId = newKxmRunId();
const payload = {
workflowId: request.workflowId,
status: "created",
promptHash: promptSha256,
repositoryIds: kxmDeclaredRepositoryIds(bundle),
executorIds: kxmDeclaredExecutorIds(bundle)
};
const event = {
schema: KXM_RUN_EVENT_SCHEMA,
eventId: newKxmEventId(),
eventType: "run.created",
projectId: context.projectId,
runId,
homeRuntimeId: context.homeRuntimeId,
sequence: 1,
commandId,
occurredAt: now,
recordedAt: now,
monotonicNs,
configRevision: revisions.configRevision,
memoryRevision,
executorPolicyRevision: revisions.executorPolicyRevision,
toolPolicyRevision: revisions.toolPolicyRevision,
payload
};
const run = {
runId,
projectId: context.projectId,
homeRuntimeId: context.homeRuntimeId,
workflowId: request.workflowId,
promptSha256,
status: "created",
configRevision: revisions.configRevision,
memoryRevision,
executorPolicyRevision: revisions.executorPolicyRevision,
toolPolicyRevision: revisions.toolPolicyRevision,
createdAt: now,
updatedAt: now
};
context.eventStore.insertRun(run);
context.eventStore.appendEvent(event);
context.eventStore.insertCommand({
commandId,
runId,
kind: "run.accept",
result: { runId, homeRuntimeId: context.homeRuntimeId, status: "created" },
recordedAt: now
});
context.eventStore.putRunPrompt(runId, request.prompt);
return { accepted: true, idempotent: false, run, event };
});
}
function foldStoredKxmRun(context, run) {
const events = context.eventStore.events(run.runId, 0, 1e6);
const planRow = context.eventStore.runPlan(run.runId);
if (!planRow && events.some((event) => event.eventType.startsWith("step.") || event.eventType.startsWith("effect.") || event.payload.status === "preparing" || event.payload.status === "running" || event.payload.status === "cancelling")) {
throw runtimeError("run_plan_missing", run.runId, "run reached preparing or later without a pinned plan");
}
const envelope2 = planRow ? loadKxmRunPlanEnvelope(context.eventStore, run) : void 0;
const state = foldKxmRunState(run, envelope2?.plan, events, envelope2 ? {
observationLookup: (attemptId, observationId) => {
const row = context.eventStore.gateObservationForAttempt(attemptId);
if (!row || row.observationId !== observationId) return void 0;
return { completeness: row.completeness };
},
gateKind: (stepId) => {
const step = envelope2.plan.steps[stepId];
if (!step || step.kind !== "gate") return void 0;
return envelope2.gates.definitions[step.gate]?.kind;
},
projectLimits: envelope2.projectLimits
} : {});
if (envelope2) verifyKxmGateEvidence(context.eventStore, run, envelope2, events, state);
assertStoredProjection(context, run);
return state;
}
function storedProjectionSchema(stateJson) {
try {
const parsed = JSON.parse(stateJson);
return typeof parsed.schema === "string" ? parsed.schema : void 0;
} catch {
return void 0;
}
}
function assertStoredProjection(context, run) {
const stored = context.eventStore.runState(run.runId);
if (!stored) return;
const schema = storedProjectionSchema(stored.state);
if (schema !== KXM_RUN_STATE_SCHEMA) {
throw runtimeError("run_projection_divergent", run.runId, "stored run_state does not match the folded projection");
}
}
function readKxmRunStatus(context, run) {
return foldStoredKxmRun(context, run).status;
}
function persistProjection(context, run, state, now) {
const canonical = kxmCanonicalJson(state);
const stored = context.eventStore.runState(run.runId);
if (stored && stored.state !== canonical) {
throw runtimeError("run_projection_divergent", run.runId, "stored run_state does not match the folded projection");
}
if (!stored) {
context.eventStore.upsertRunState({
runId: run.runId,
lastSequence: context.eventStore.nextSequence(run.runId) - 1,
state: canonical
});
}
const updated = { ...run, status: state.status, updatedAt: now };
if (run.status !== state.status) context.eventStore.updateRunStatus(run.runId, state.status, now);
return updated;
}
function rebuildKxmRunProjection(context, runId) {
const stored = context.eventStore.run(runId);
if (!stored) throw runtimeError("run_unknown", runId, "run does not exist in this event store");
const state = foldStoredKxmRun(context, stored);
const events = context.eventStore.events(runId, 0, 1e6);
if (events.length === 0) throw runtimeError("run_events_corrupt", runId, "run has no events");
const last = events[events.length - 1];
return persistProjection(context, stored, state, last.occurredAt);
}
function projectKxmRunReadOnly(context, runId) {
const stored = context.eventStore.run(runId);
if (!stored) throw runtimeError("run_unknown", runId, "run does not exist in this event store");
const state = foldStoredKxmRun(context, stored);
const events = context.eventStore.events(runId, 0, 1e6);
if (events.length === 0) throw runtimeError("run_events_corrupt", runId, "run has no events");
const last = events[events.length - 1];
return { ...stored, status: state.status, updatedAt: last.occurredAt };
}
function persistKxmRunState(context, runId, state, lastSequence) {
const stored = context.eventStore.runState(runId);
if (stored) {
const schema = storedProjectionSchema(stored.state);
if (schema !== KXM_RUN_STATE_SCHEMA) {
throw runtimeError("run_projection_divergent", runId, "stored run_state does not match the folded projection");
}
}
context.eventStore.upsertRunState({
runId,
lastSequence,
state: kxmCanonicalJson(state)
});
}
function cancelKxmRun(context, runId, options = {}) {
const commandId = options.commandId ?? newKxmCommandId();
const now = options.now ?? (/* @__PURE__ */ new Date()).toISOString();
const monotonicNs = options.monotonicNs ?? kxmMonotonicNs();
const abortControllers = [];
const result = context.eventStore.transaction(() => {
const prior = context.eventStore.command(commandId);
if (prior) {
if (prior.kind !== "run.cancel" || prior.runId !== runId) {
throw runtimeError("run_command_conflict", commandId, `command ${commandId} was already used for ${prior.kind}${prior.runId === runId ? "" : " on a different run"}`);
}
const run2 = context.eventStore.run(prior.runId);
if (!run2) throw runtimeError("run_command_corrupt", commandId, "idempotent command references a missing run");
return { run: run2, idempotent: true, events: [] };
}
const run = context.eventStore.run(runId);
if (!run) throw runtimeError("run_unknown", runId, "run does not exist in this event store");
const folded = foldStoredKxmRun(context, run);
if (isTerminalRunStatus(folded.status) || folded.status === "cancelling") {
context.eventStore.insertCommand({
commandId,
runId,
kind: "run.cancel",
result: { runId, status: folded.status },
recordedAt: now
});
return { run: { ...run, status: folded.status }, idempotent: true, events: [] };
}
const events = [];
let sequence = context.eventStore.nextSequence(runId);
let nextMono = monotonicNs;
const push2 = (eventType, payload) => {
const event = {
...kxmEventBase(context, run, now, nextMono, commandId),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
};
nextMono = kxmIncrementMonotonicNs(nextMono);
events.push(event);
return event;
};
const cancelReason = options.reason ?? "operator_cancel";
const activeAttempt = Boolean(folded.currentStep?.attemptId) || kxmFoldPanelAttemptIds(folded.currentStep).length > 0;
const cancelPayload = {
actor: { kind: "runtime", id: context.homeRuntimeId },
reason: cancelReason
};
if (cancelReason === "budget_run_duration") {
if (!options.budget) {
throw runtimeError("run_events_illegal", runId, "budget_run_duration requires a budget payload");
}
cancelPayload.budget = options.budget;
}
push2("run.cancel_requested", cancelPayload);
let status = "cancelled";
if (folded.status === "running" && activeAttempt) {
status = "cancelling";
push2("run.status_changed", { status: "cancelling", reason: cancelReason });
const attemptIds = new Set(kxmFoldPanelAttemptIds(folded.currentStep));
if (folded.currentStep?.attemptId) attemptIds.add(folded.currentStep.attemptId);
for (const attemptId of attemptIds) {
const capability = context.eventStore.capabilityByAttempt(attemptId);
if (capability && capability.state === "issued") {
context.eventStore.settleCapability(attemptId, "revoked");
}
}
for (const owned of kxmAttemptControllers(context.eventStore.path, runId)) {
abortControllers.push(owned.controller);
}
} else if (folded.status === "blocked_uncertain") {
push2("run.status_changed", { status: "cancelling", reason: cancelReason });
const attemptId = folded.currentStep?.attemptId;
if (attemptId) {
const capability = context.eventStore.capabilityByAttempt(attemptId);
if (capability && (capability.state === "issued" || capability.state === "revoked")) {
context.eventStore.settleCapability(attemptId, "revoked");
}
resolveKxmGateHold(context.eventStore.path, runId, attemptId);
}
for (const owned of kxmAttemptControllers(context.eventStore.path, runId)) {
abortControllers.push(owned.controller);
}
push2("run.status_changed", { status: "cancelled", reason: cancelReason });
status = "cancelled";
} else if (folded.status === "running" && !activeAttempt) {
push2("run.status_changed", { status: "cancelling", reason: cancelReason });
push2("run.status_changed", { status: "cancelled", reason: cancelReason });
} else {
push2("run.status_changed", { status: "cancelled", reason: cancelReason });
}
for (const event of events) context.eventStore.appendEvent(event);
const nextState = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, nextState, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(runId, status, now);
context.eventStore.insertCommand({
commandId,
runId,
kind: "run.cancel",
result: { runId, status },
recordedAt: now
});
return { run: { ...run, status, updatedAt: now }, idempotent: false, events };
});
for (const controller of abortControllers) controller.abort();
return result;
}
function kxmRunRevisionDrift(run, bundle) {
return {
configDrift: run.configRevision !== bundle.configRevision,
currentRevision: bundle.configRevision,
pinnedRevision: run.configRevision
};
}
function assertKxmConfigError(error) {
if (!(error instanceof KxmConfigError)) throw error;
}
// plugins/kxm/src/runtime-supervisor.ts
import { spawn as spawn3 } from "node:child_process";
import { createHash as createHash16, createHmac, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
import { chmodSync as chmodSync2, existsSync as existsSync20, lstatSync as lstatSync6, mkdirSync as mkdirSync10, readFileSync as readFileSync17, renameSync as renameSync5, rmSync as rmSync4, writeFileSync as writeFileSync10 } from "node:fs";
import { createServer } from "node:http";
import { dirname as dirname13, isAbsolute as isAbsolute8, join as join22 } from "node:path";
// plugins/kxm/src/oneshot-evidence.ts
import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";
import { lstatSync as lstatSync4, readdirSync as readdirSync5, readFileSync as readFileSync6 } from "node:fs";
import { lstat, mkdir, open, rename } from "node:fs/promises";
import { join as join9 } from "node:path";
var ONESHOT_EVIDENCE_SCHEMA = "kxm.oneshot-evidence.v2";
var RETIRED_ONESHOT_EVIDENCE_SCHEMAS = /* @__PURE__ */ new Set(["kxm.oneshot-evidence.v1"]);
var TEXT_LIMIT = 4 * 1024 * 1024;
var ARGV_LIMIT = 64 * 1024;
var RECORD_LIMIT = 16 * 1024 * 1024;
var digest = (value) => `sha256:${createHash10("sha256").update(value).digest("hex")}`;
function parseOneShotEvidenceRecord(bytes) {
let parsed;
try {
parsed = JSON.parse(bytes);
} catch {
throw new Error("oneshot_evidence_record_invalid");
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new Error("oneshot_evidence_record_invalid");
}
const schema = parsed.schema;
if (typeof schema !== "string") throw new Error("oneshot_evidence_record_invalid");
if (RETIRED_ONESHOT_EVIDENCE_SCHEMAS.has(schema)) throw new Error("oneshot_evidence_schema_retired");
if (schema !== ONESHOT_EVIDENCE_SCHEMA) throw new Error("oneshot_evidence_schema_unknown");
return parsed;
}
function oneShotEvidenceRoot() {
return join9(kxmUserStateRoot(), "runtime", "oneshot-evidence");
}
function readOneShotObservedChildExit(runId, attemptId, root = oneShotEvidenceRoot()) {
let names3;
try {
names3 = readdirSync5(root);
} catch {
return void 0;
}
let seenTrue = false;
let seenFalse = false;
const capped = names3.slice(0, 4096);
for (const name of capped) {
if (!name.startsWith("evd_")) continue;
const dir = join9(root, name);
try {
const info = lstatSync4(dir);
if (!info.isDirectory() || info.isSymbolicLink()) continue;
const intent = parseOneShotEvidenceRecord(readFileSync6(join9(dir, "intent.json"), "utf8"));
if (intent.runId !== runId || intent.attemptId !== attemptId) continue;
const result = parseOneShotEvidenceRecord(readFileSync6(join9(dir, "result.json"), "utf8"));
if (result.observedChildExit === true) seenTrue = true;
else if (result.observedChildExit === false) seenFalse = true;
} catch {
}
}
if (seenFalse) return false;
if (seenTrue) return true;
return void 0;
}
async function beginOneShotEvidence(root, intent, sensitive) {
await mkdir(root, { recursive: true, mode: 448 });
const stat = await lstat(root);
if (!stat.isDirectory() || stat.isSymbolicLink() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
throw new Error("oneshot_evidence_root_not_private");
}
const id = `evd_${randomUUID3().replaceAll("-", "")}`;
const dir = join9(root, id);
await mkdir(dir, { mode: 448 });
const secrets = [...new Set(sensitive.filter((value) => value.length >= 8))].sort((a, b) => b.length - a.length);
const redact = (value) => {
let text = value;
for (const secret of secrets) text = text.replaceAll(secret, "[REDACTED]");
return text.replace(/(\b(?:authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret)\b["']?\s*[:=]\s*["']?)(?:Bearer\s+)?[^\s"',;}]+/gi, "$1[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [REDACTED]");
};
const bounded = (value, max = TEXT_LIMIT) => {
const bytes = Buffer.from(redact(value));
return { text: bytes.subarray(0, max).toString("utf8"), truncated: bytes.length > max, sha256: digest(redact(value)) };
};
const write = async (name, value) => {
const current = await lstat(dir);
if (!current.isDirectory() || current.isSymbolicLink() || process.platform !== "win32" && ((current.mode & 63) !== 0 || current.uid !== process.getuid?.())) {
throw new Error("oneshot_evidence_directory_changed");
}
const bytes = JSON.stringify(value);
if (Buffer.byteLength(bytes) > RECORD_LIMIT) throw new Error("oneshot_evidence_record_limit");
parseOneShotEvidenceRecord(bytes);
const target = join9(dir, name);
const partial = `${target}.partial`;
const file = await open(partial, "wx", 384);
try {
await file.writeFile(bytes);
await file.sync();
} finally {
await file.close();
}
await rename(partial, target);
if (process.platform !== "win32") {
const directory = await open(dir, "r");
try {
await directory.sync();
} finally {
await directory.close();
}
}
return digest(bytes);
};
await write("intent.json", {
schema: ONESHOT_EVIDENCE_SCHEMA,
id,
recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
runId: intent.runId,
stepId: intent.stepId,
attemptId: intent.attemptId,
assignmentId: intent.assignmentId,
harness: intent.harness,
provider: intent.provider,
requestedModel: intent.model,
...intent.timeoutMs !== void 0 ? { timeoutMs: intent.timeoutMs } : {},
cwd: intent.cwd,
command: redact(intent.command),
argv: bounded(JSON.stringify(intent.args), ARGV_LIMIT),
stdin: intent.input === void 0 ? null : bounded(intent.input),
env: null,
acceptance: false
});
let finished = false;
return {
id,
async finish(result, observation) {
if (finished) throw new Error("oneshot_evidence_already_finished");
finished = true;
return write("result.json", {
schema: ONESHOT_EVIDENCE_SCHEMA,
id,
recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
stdout: bounded(result.stdout),
stderr: bounded(result.stderr),
code: result.code,
signal: result.signal ?? null,
started: result.started ?? null,
observedChildExit: result.observedChildExit ?? null,
terminationRequested: result.terminationRequested ?? null,
unverifiedDescendants: result.unverifiedDescendants ?? null,
error: result.error ? bounded(result.error.message) : null,
observation: bounded(JSON.stringify(observation)),
acceptance: false
});
}
};
}
// plugins/kxm/src/prices.ts
var import_yaml4 = __toESM(require_dist(), 1);
import { createHash as createHash11 } from "node:crypto";
import { existsSync as existsSync9, readFileSync as readFileSync7, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
import { join as join10 } from "node:path";
// plugins/kxm/src/price-calc.ts
var PRICES_SCHEMA = "kxm.prices.v1";
function findModelPrice(catalog, model, provider) {
const normalizedModel = model.trim().toLowerCase();
const normalizedProvider = provider?.trim().toLowerCase();
for (const entry of catalog.models) {
if (normalizedProvider && entry.provider.toLowerCase() !== normalizedProvider) continue;
if (entry.id.toLowerCase() === normalizedModel || entry.model.toLowerCase() === normalizedModel) {
return entry;
}
if (entry.aliases?.some((a) => a.toLowerCase() === normalizedModel)) {
return entry;
}
}
return void 0;
}
function calculateModelCost(catalog, params) {
const row = findModelPrice(catalog, params.model, params.provider);
if (!row || row.tiers.length === 0) return void 0;
if (catalog.currency !== void 0 && catalog.currency !== "USD") return void 0;
const validCount = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
const tokensIn = params.tokensIn;
const tokensOut = params.tokensOut;
const cacheRead = params.cacheReadTokens;
const cacheWrite = params.cacheWriteTokens;
if (!validCount(tokensIn) || !validCount(tokensOut) || !validCount(cacheRead) || !validCount(cacheWrite)) return void 0;
const context = params.contextTokens;
if (context != null && !validCount(context)) return void 0;
const selectedTier = context == null ? row.tiers.length === 1 && row.tiers[0].upToContextTokens == null ? row.tiers[0] : void 0 : row.tiers.find((tier) => tier.upToContextTokens == null || context <= tier.upToContextTokens);
if (!selectedTier || cacheRead > 0 && selectedTier.cacheReadPerMillion == null || cacheWrite > 0 && selectedTier.cacheWritePerMillion == null) return void 0;
const cost = tokensIn / 1e6 * selectedTier.inputPerMillion + tokensOut / 1e6 * selectedTier.outputPerMillion + cacheRead / 1e6 * (selectedTier.cacheReadPerMillion ?? 0) + cacheWrite / 1e6 * (selectedTier.cacheWritePerMillion ?? 0);
if (!Number.isFinite(cost) || cost < 0) return void 0;
const priceRef = `${catalog.date}#${row.id}`;
return {
costUsd: Math.round(cost * 1e6) / 1e6,
priceRef
};
}
// plugins/kxm/src/prices.ts
function hashPriceCatalog(catalog) {
const canonical = {
schema: catalog.schema,
date: catalog.date,
currency: catalog.currency ?? "USD",
models: catalog.models.map((m) => ({
id: m.id,
provider: m.provider,
model: m.model,
aliases: m.aliases ? [...m.aliases].sort() : [],
tiers: m.tiers.map((t) => ({
upToContextTokens: t.upToContextTokens ?? null,
inputPerMillion: t.inputPerMillion,
outputPerMillion: t.outputPerMillion,
cacheReadPerMillion: t.cacheReadPerMillion ?? null,
cacheWritePerMillion: t.cacheWritePerMillion ?? null
}))
})).sort((a, b) => a.id.localeCompare(b.id))
};
return createHash11("sha256").update(JSON.stringify(canonical), "utf8").digest("hex");
}
function parsePriceCatalog(text) {
const parsed = (0, import_yaml4.parse)(text);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new Error("price catalog must be an object");
}
if (parsed.schema !== PRICES_SCHEMA) {
throw new Error(`price catalog schema must be ${PRICES_SCHEMA}`);
}
if (typeof parsed.date !== "string" || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(parsed.date)) {
throw new Error("price catalog date must be YYYY-MM-DD");
}
if (!Number.isFinite(Date.parse(parsed.date)) || new Date(parsed.date).toISOString().slice(0, 10) !== parsed.date) {
throw new Error("price catalog date must be a valid calendar date");
}
if (parsed.currency !== void 0 && parsed.currency !== "USD") throw new Error("price catalog currency must be USD");
if (typeof parsed.sha256 !== "string" || !/^(?:sha256:)?[a-f0-9]{64}$/.test(parsed.sha256)) {
throw new Error("price catalog sha256 must be a 64-character hex digest");
}
if (!Array.isArray(parsed.models) || parsed.models.length === 0) {
throw new Error("price catalog models must be a non-empty array");
}
const models = parsed.models.map((item, index) => {
if (!item || typeof item !== "object" || Array.isArray(item)) {
throw new Error(`price catalog model at index ${index} must be an object`);
}
const m = item;
if (typeof m.id !== "string" || !m.id) {
throw new Error(`price catalog model at index ${index} must have a non-empty id`);
}
if (typeof m.provider !== "string" || !m.provider) {
throw new Error(`price catalog model at index ${index} must have a non-empty provider`);
}
if (typeof m.model !== "string" || !m.model) {
throw new Error(`price catalog model at index ${index} must have a non-empty model`);
}
const aliases = Array.isArray(m.aliases) ? m.aliases.filter((a) => typeof a === "string" && Boolean(a)) : void 0;
if (!Array.isArray(m.tiers) || m.tiers.length === 0) {
throw new Error(`price catalog model ${m.id} must have at least one tier`);
}
const rawTiers = m.tiers;
let previousBound = 0;
const tiers = rawTiers.map((tItem, tIndex) => {
if (!tItem || typeof tItem !== "object" || Array.isArray(tItem)) {
throw new Error(`tier at index ${tIndex} for model ${m.id} must be an object`);
}
const t = tItem;
const rate = (field, short, required2 = false) => {
const value = t[field] !== void 0 ? t[field] : t[short];
if (value == null && !required2) return null;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
throw new Error(`tier ${tIndex} for model ${m.id} requires finite non-negative ${field}`);
}
return value;
};
const bound = t.upToContextTokens ?? null;
if (bound === null) {
if (tIndex !== rawTiers.length - 1) throw new Error("unbounded price tier must be last");
} else {
if (typeof bound !== "number" || !Number.isSafeInteger(bound) || bound <= previousBound) throw new Error("price tier bounds must be positive and strictly increasing");
previousBound = bound;
}
return {
upToContextTokens: bound,
inputPerMillion: rate("inputPerMillion", "input", true),
outputPerMillion: rate("outputPerMillion", "output", true),
cacheReadPerMillion: rate("cacheReadPerMillion", "cacheRead"),
cacheWritePerMillion: rate("cacheWritePerMillion", "cacheWrite")
};
});
return {
id: m.id,
provider: m.provider,
model: m.model,
aliases,
tiers
};
});
const catalog = {
schema: PRICES_SCHEMA,
date: parsed.date,
sha256: parsed.sha256.replace(/^sha256:/, ""),
currency: typeof parsed.currency === "string" ? parsed.currency : "USD",
models
};
if (new Set(models.map((row) => row.id)).size !== models.length) throw new Error("duplicate price catalog model id");
if (hashPriceCatalog(catalog) !== catalog.sha256) throw new Error("price catalog hash mismatch");
return catalog;
}
function loadPriceCatalog(rootOrPath) {
const candidatePath = existsSync9(join10(rootOrPath, ".kxm", "prices.yaml")) ? join10(rootOrPath, ".kxm", "prices.yaml") : existsSync9(join10(rootOrPath, "prices.yaml")) ? join10(rootOrPath, "prices.yaml") : existsSync9(rootOrPath) && statSync2(rootOrPath).isFile() ? rootOrPath : void 0;
if (!candidatePath || !existsSync9(candidatePath)) {
return void 0;
}
const content = readFileSync7(candidatePath, "utf8");
return parsePriceCatalog(content);
}
function loadPriceCatalogForEstimate(options) {
let catalog;
try {
catalog = options?.priceCatalog ? parsePriceCatalog(JSON.stringify(options.priceCatalog)) : loadPriceCatalog(options?.projectRoot ?? process.cwd());
} catch {
return { catalog: void 0, unavailable: true, stale: false };
}
if (catalog && catalog.date !== (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
return { catalog: void 0, unavailable: false, stale: true };
}
return { catalog, unavailable: false, stale: false };
}
// plugins/kxm/src/engine.ts
var import_yaml11 = __toESM(require_dist(), 1);
import { createHash as createHash15, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
import { existsSync as existsSync15, readFileSync as readFileSync13 } from "node:fs";
import { join as join18 } from "node:path";
// plugins/kxm/src/routes.ts
var import_yaml7 = __toESM(require_dist(), 1);
import { existsSync as existsSync11, readFileSync as readFileSync9, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5, readdirSync as readdirSync6 } from "node:fs";
import { join as join12 } from "node:path";
// plugins/kxm/src/role.ts
var import_yaml6 = __toESM(require_dist(), 1);
// plugins/kxm/src/config.ts
var import_yaml5 = __toESM(require_dist(), 1);
import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "node:fs";
import { tmpdir, homedir as homedir2 } from "node:os";
import { dirname as dirname6, join as join11, resolve as resolve7 } from "node:path";
var KXM_CONFIG_SCHEMA = "kxm.config.v1";
var KxmHubConfigError = class extends Error {
code = "hub_config_invalid";
constructor(message) {
super(message);
this.name = "KxmHubConfigError";
}
};
var HUB_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
var HUB_OP_REF = /^op:\/\/\S+\/\S+\/\S+$/;
var LITERAL_SECRET_KEY = /^(token|secret|password|authToken|auth_token|apiKey|api_key|api_token|bearer|credential|access_token)$/i;
function isHubKeyEnvName(value) {
return HUB_ENV_NAME.test(value);
}
function isHubOpReference(value) {
return HUB_OP_REF.test(value);
}
var IMPROVEMENT_PROMOTION_POLICIES = ["manual_pr", "critic_quorum", "auto_threshold"];
var DEFAULT_KXM_CONFIG = {
schema: KXM_CONFIG_SCHEMA,
user: {
theme: "dark",
preferredCritics: ["reviewer-arch", "reviewer-cli"],
tokenBudget: 16e3
},
defaults: {
workflow: "software-engineering/feature-implementation",
harness: "pi"
},
dash: {
defaultScreen: "agents",
refreshIntervalMs: 1e3,
autoOpen: false
},
sync: {
defaultTracker: "none"
},
hub: {
autoStart: "background"
},
improvement: {
promotionPolicy: "manual_pr",
telemetryHalfLifeDays: 14,
autoThreshold: {
minRuns: 10,
minPassRate: 0.95,
minCostSavings: 0.5
}
},
routing: {
shadowExecution: {
enabled: false,
sampleRate: 0.05,
candidateModels: []
},
circuitBreaker: {
mode: "soft_demotion",
failureThreshold: 3,
windowSeconds: 3600,
cooldownSeconds: 1800,
penaltyMultiplier: 5
}
},
telemetry: {
federated: true,
anonymize: true
}
};
function userConfigDirectory(overrideDir) {
if (overrideDir) return resolve7(overrideDir);
return resolve7(process.env.KXM_USER_CONFIG_DIR?.trim() || join11(homedir2(), ".config", "kxm"));
}
function repoConfigDirectory(repoRoot) {
return resolve7(repoRoot, ".kxm");
}
function deepMerge(target, source) {
const result = { ...target };
for (const [key, val] of Object.entries(source)) {
if (val && typeof val === "object" && !Array.isArray(val)) {
const existing = result[key] && typeof result[key] === "object" && !Array.isArray(result[key]) ? result[key] : {};
result[key] = deepMerge(existing, val);
} else if (val !== void 0) {
result[key] = val;
}
}
return result;
}
function literalSecretMessage(path) {
return `refusing literal hub token at ${path}: store an op:// reference (key.op) or an environment variable name (key.env), never the token`;
}
function rejectLiteralHubSecrets(value, path) {
if (Array.isArray(value)) {
value.forEach((item, index) => rejectLiteralHubSecrets(item, `${path}[${index}]`));
return;
}
if (!value || typeof value !== "object") return;
for (const [key, child] of Object.entries(value)) {
const childPath = `${path}.${key}`;
if (typeof child === "string" && (key === "key" || LITERAL_SECRET_KEY.test(key))) {
throw new KxmHubConfigError(literalSecretMessage(childPath));
}
if (child && typeof child === "object") rejectLiteralHubSecrets(child, childPath);
}
}
function parseKeyRef(raw, path) {
if (raw === void 0) return void 0;
if (typeof raw === "string") throw new KxmHubConfigError(literalSecretMessage(path));
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new KxmHubConfigError(`${path} must be a key reference with op and/or env, never a token`);
}
const row = raw;
for (const key of Object.keys(row)) {
if (key !== "op" && key !== "env") {
throw new KxmHubConfigError(literalSecretMessage(`${path}.${key}`));
}
}
const ref = {};
if (row.op !== void 0) {
if (typeof row.op !== "string" || !isHubOpReference(row.op)) {
throw new KxmHubConfigError(`${path}.op must be an op://vault/item/field reference, not a token`);
}
ref.op = row.op;
}
if (row.env !== void 0) {
if (typeof row.env !== "string" || !isHubKeyEnvName(row.env)) {
throw new KxmHubConfigError(`${path}.env must be an environment variable name, not a token`);
}
ref.env = row.env;
}
if (!ref.op && !ref.env) throw new KxmHubConfigError(`${path} needs key.op, key.env, or both`);
return ref;
}
function parseEndpoint(raw, path) {
if (raw === void 0) return void 0;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new KxmHubConfigError(`${path} must be an object with url, project, and key`);
}
const row = raw;
const endpoint = {};
if (row.url !== void 0) {
if (typeof row.url !== "string" || !isHubUrl(row.url)) {
throw new KxmHubConfigError(`${path}.url must be an http or https URL without credentials, query, or fragment`);
}
endpoint.url = row.url.replace(/\/$/, "");
}
if (row.project !== void 0) {
if (typeof row.project !== "string" || !isHubProjectId(row.project)) {
throw new KxmHubConfigError(`${path}.project must be a single-line project id, not a token`);
}
endpoint.project = row.project.trim();
}
const key = parseKeyRef(row.key, `${path}.key`);
if (key) endpoint.key = key;
for (const name of Object.keys(row)) {
if (name !== "url" && name !== "project" && name !== "key") {
if (typeof row[name] === "string") throw new KxmHubConfigError(literalSecretMessage(`${path}.${name}`));
throw new KxmHubConfigError(`${path}.${name} is not a hub endpoint field`);
}
}
return endpoint;
}
function isHubUrl(raw) {
try {
const parsed = new URL(raw);
return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.username === "" && parsed.password === "" && parsed.search === "" && parsed.hash === "" && !raw.includes("?") && !raw.includes("#");
} catch {
return false;
}
}
function isHubProjectId(raw) {
const value = raw.trim();
return value.length > 0 && value.length <= 200 && !/[\s\r\n]/.test(value);
}
function parseProjectMap(raw) {
if (raw === void 0) return void 0;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new KxmHubConfigError("hub.projects must be a map of project id to key reference, never a token");
}
const projects = {};
for (const [project, value] of Object.entries(raw)) {
if (!isHubProjectId(project)) {
throw new KxmHubConfigError(`hub.projects key ${JSON.stringify(project)} must be a project id, not a token`);
}
const ref = parseKeyRef(value, `hub.projects.${project}`);
if (!ref) throw new KxmHubConfigError(`hub.projects.${project} needs an op:// reference or an environment variable name`);
projects[project.trim()] = ref;
}
return projects;
}
function normalizeHubConfig(raw) {
const autoStart = raw?.autoStart;
const hub = {
autoStart: autoStart === "off" || autoStart === "background" ? autoStart : DEFAULT_KXM_CONFIG.hub.autoStart
};
if (raw === void 0) return hub;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new KxmHubConfigError("hub must be an object");
}
rejectLiteralHubSecrets(raw, "hub");
const row = raw;
if (row.mode !== void 0) {
if (row.mode !== "local" && row.mode !== "cloud") {
throw new KxmHubConfigError("hub.mode must be local or cloud");
}
hub.mode = row.mode;
}
const local = parseEndpoint(row.local, "hub.local");
const cloud = parseEndpoint(row.cloud, "hub.cloud");
const projects = parseProjectMap(row.projects);
if (local) hub.local = local;
if (cloud) hub.cloud = cloud;
if (projects && Object.keys(projects).length > 0) hub.projects = projects;
return hub;
}
function findConfigRoot(start) {
let dir = resolve7(start);
for (; ; ) {
if (existsSync10(join11(dir, ".kxm", "project.yaml")) || existsSync10(join11(dir, ".kxm", "config.yaml"))) return dir;
const parent = dirname6(dir);
if (parent === dir) return resolve7(start);
dir = parent;
}
}
function userConfigDirForEnv(env) {
const explicit = env.KXM_USER_CONFIG_DIR?.trim();
if (explicit) return explicit;
if (env === process.env) return void 0;
return join11(tmpdir(), "kxm-no-user-config");
}
function loadHubSettings(start, env = process.env) {
const userConfigDir = userConfigDirForEnv(env);
return loadKxmConfig(findConfigRoot(start), userConfigDir === void 0 ? {} : { userConfigDir }).hub;
}
function recordOf(raw) {
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
}
function finiteNumber(value) {
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function normalizeImprovementConfig(raw) {
const value = recordOf(raw);
const threshold = recordOf(value.autoThreshold);
const policy = value.promotionPolicy;
const halfLife = finiteNumber(value.telemetryHalfLifeDays);
const minRuns = finiteNumber(threshold.minRuns);
const minPassRate = finiteNumber(threshold.minPassRate);
const minCostSavings = finiteNumber(threshold.minCostSavings);
return {
promotionPolicy: IMPROVEMENT_PROMOTION_POLICIES.includes(policy) ? policy : "manual_pr",
telemetryHalfLifeDays: halfLife !== void 0 && halfLife > 0 && halfLife <= 3650 ? halfLife : 14,
autoThreshold: {
minRuns: minRuns !== void 0 && Number.isInteger(minRuns) && minRuns >= 1 && minRuns <= 1e6 ? minRuns : 10,
minPassRate: minPassRate !== void 0 && minPassRate >= 0 && minPassRate <= 1 ? minPassRate : 0.95,
minCostSavings: minCostSavings !== void 0 && minCostSavings >= 0 ? minCostSavings : 0.5
}
};
}
function loadKxmConfig(repoRoot = process.cwd(), options = {}) {
const userDir = userConfigDirectory(options.userConfigDir);
const userConfigFile = join11(userDir, "config.yaml");
const repoDir = repoConfigDirectory(repoRoot);
const repoConfigFile = join11(repoDir, "config.yaml");
let userRaw = {};
let userLoadedPath;
if (existsSync10(userConfigFile)) {
try {
const text = readFileSync8(userConfigFile, "utf8");
userRaw = (0, import_yaml5.parse)(text) ?? {};
userLoadedPath = userConfigFile;
} catch (error) {
throw new Error(`invalid user config YAML at ${userConfigFile}`, { cause: error });
}
}
let repoRaw = {};
let repoLoadedPath;
if (existsSync10(repoConfigFile)) {
try {
const text = readFileSync8(repoConfigFile, "utf8");
repoRaw = (0, import_yaml5.parse)(text) ?? {};
repoLoadedPath = repoConfigFile;
} catch (error) {
throw new Error(`invalid project config YAML at ${repoConfigFile}`, { cause: error });
}
}
const baseCopy = JSON.parse(JSON.stringify(DEFAULT_KXM_CONFIG));
const mergedUser = deepMerge(baseCopy, userRaw);
const mergedAll = deepMerge(mergedUser, repoRaw);
return {
schema: KXM_CONFIG_SCHEMA,
user: mergedAll.user ?? {},
defaults: mergedAll.defaults ?? {},
dash: mergedAll.dash ?? {},
sync: mergedAll.sync ?? {},
hub: normalizeHubConfig(mergedAll.hub),
improvement: normalizeImprovementConfig(mergedAll.improvement),
routing: mergedAll.routing ?? DEFAULT_KXM_CONFIG.routing,
telemetry: mergedAll.telemetry ?? DEFAULT_KXM_CONFIG.telemetry,
loadedFrom: {
userConfigPath: userLoadedPath,
repoConfigPath: repoLoadedPath
}
};
}
// plugins/kxm/src/routes.ts
var RETIRED_POLICY = ".kxm/producers.yaml";
var empty = () => ({ schema: "kxm.routes.v2", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), admitted: [], disabled: [] });
function loadRoutePolicy(root) {
if (existsSync11(join12(root, RETIRED_POLICY))) throw new Error(`retired ${RETIRED_POLICY} present; use .kxm/routes.yaml (kxm.routes.v2)`);
const path = join12(root, ".kxm", "routes.yaml");
if (!existsSync11(path)) return empty();
const value = (0, import_yaml7.parse)(readFileSync9(path, "utf8"));
if (value?.schema !== "kxm.routes.v2" || !Array.isArray(value.admitted)) throw new Error("invalid .kxm/routes.yaml");
return { schema: "kxm.routes.v2", updatedAt: typeof value.updatedAt === "string" ? value.updatedAt : (/* @__PURE__ */ new Date()).toISOString(), admitted: value.admitted.filter((x) => typeof x === "string"), disabled: Array.isArray(value.disabled) ? value.disabled.filter((x) => typeof x === "string") : [] };
}
function listRoleBindings(root) {
const dir = join12(root, ".kxm", "roles");
const result = {};
if (!existsSync11(dir)) return result;
for (const file of readdirSync6(dir).filter((name) => name.endsWith(".yaml"))) {
const role = file.slice(0, -5);
const value = (0, import_yaml7.parse)(readFileSync9(join12(dir, file), "utf8"));
result[role] = (value.roster ?? []).map((entry) => entry.route).filter((route) => typeof route === "string");
}
return result;
}
// plugins/kxm/src/route-fallback.ts
var import_yaml8 = __toESM(require_dist(), 1);
import { existsSync as existsSync12, readdirSync as readdirSync7, readFileSync as readFileSync10 } from "node:fs";
import { join as join13 } from "node:path";
// plugins/kxm/src/route-switch.ts
var WALKABLE_CLASSES = ["rate_limit", "transport", "provider_unavailable", "context_overflow"];
var EFFORTS2 = /* @__PURE__ */ new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
// plugins/kxm/src/route-fallback.ts
var CARRY_ROLES = /* @__PURE__ */ new Set(["user", "assistant", "tool"]);
var MAX_CARRY_MESSAGES = 8;
var MAX_CARRY_TEXT = 2e3;
var MAX_CARRY_TOTAL = 8e3;
var DEFAULT_MAX_SWITCHES = 1;
function classifyRouteFailure(input) {
const code = (input.code ?? "").toLowerCase();
const text = `${code} ${input.text ?? ""}`.toLowerCase();
const name = (input.name ?? "").toLowerCase();
const status = input.httpStatus;
const result = (failureClass) => ({
class: failureClass,
walkable: WALKABLE_CLASSES.includes(failureClass)
});
if (name === "aborterror" || /\b(?:user_cancelled|cancelled|cancellation)\b/.test(text) || code === "process_aborted" || text.includes("abort")) {
return result("cancelled");
}
if (/policy_refusal|content_policy|tool_policy|usage policy|safety/.test(text) || text.includes("policy refusal")) {
return result("policy_refusal");
}
if (code.includes("not_authenticated") || /unauthori[sz]ed|authentication|invalid api key|auth_failed|\bauth\b/.test(text) || status === 401 || status === 403) {
return result("auth");
}
if (/permission_profile_unaudited|writer_profile_unaudited|tool_policy/.test(text)) {
return result("tool_policy");
}
if (/harness_unhosted_model|unhosted|does not host/.test(text)) {
return result("unhosted_model");
}
if (code.startsWith("gate_") || text.includes("gate_unsupported") || text.includes("gate_failed")) {
return result("gate");
}
if (code === "producer_route_not_admitted" || text.includes("not_admitted") || text.includes("not admitted")) {
return result("admission");
}
if (status === 413 || /context_overflow|context length|context window|maximum context|token limit|prompt too long|context overflow/.test(text)) {
return result("context_overflow");
}
if (status === 429 || /rate_limit|rate limit|ratelimit|too many requests/.test(text)) {
return result("rate_limit");
}
if (status === 408 || status === 502 || status === 504 || code === "process_timeout" || /etimedout|econnreset|econnrefused|enotfound|eai_again|socket hang up|\btimeout\b|timed out|\btransport\b/.test(text)) {
return result("transport");
}
if (status === 500 || status === 503 || /provider_unavailable|model unavailable|service unavailable|overloaded|model_not_found|no available model/.test(text)) {
return result("provider_unavailable");
}
return result("unknown");
}
function parseFallbackPolicy(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
const record2 = value;
const onErrorRaw = record2.onError;
if (!Array.isArray(onErrorRaw) || onErrorRaw.length === 0) return void 0;
if (new Set(onErrorRaw).size !== onErrorRaw.length) return void 0;
const onError = [];
for (const item of onErrorRaw) {
if (typeof item !== "string" || !WALKABLE_CLASSES.includes(item)) return void 0;
onError.push(item);
}
let maxSwitches = DEFAULT_MAX_SWITCHES;
if (record2.maxSwitches !== void 0) {
if (!Number.isInteger(record2.maxSwitches) || record2.maxSwitches < 0) return void 0;
maxSwitches = record2.maxSwitches;
}
let revert = "next_run";
if (record2.revert !== void 0) {
if (record2.revert !== "next_run" && record2.revert !== "never") return void 0;
revert = record2.revert;
}
return { onError, maxSwitches, revert };
}
function admittedSelector(model, admitted, disabled) {
const candidates = [model.model, `${model.vendor}/${model.model}`, `${model.harness}/${model.model}`];
const selector = candidates.find((candidate) => admitted.has(candidate));
if (!selector || disabled.has(selector)) return void 0;
return selector;
}
function splitSelector(selector) {
const slash = selector.indexOf("/");
if (slash <= 0 || slash === selector.length - 1) return void 0;
return { provider: selector.slice(0, slash), model: selector.slice(slash + 1) };
}
function eligible(model, admitted, disabled, liveWrite) {
if (model.status !== "admitted" || !model.hosted) return void 0;
if (liveWrite && (!model.permissions.includes("edit") || !model.writerReady || !model.onWriterRoster)) return void 0;
const selector = admittedSelector(model, admitted, disabled);
if (!selector) return void 0;
const parts = splitSelector(selector);
if (!parts) return void 0;
return {
routeId: model.routeId,
harness: model.harness,
provider: parts.provider,
model: parts.model,
selector,
vendor: model.vendor,
permissions: model.permissions,
priority: model.priority
};
}
function selectorsFor2(fallback, models) {
if (fallback.profile) {
const model = models.find((item) => item.routeId === fallback.profile);
return model ? [model] : [];
}
if (fallback.tag) {
const required2 = new Set(fallback.capabilities ?? []);
return models.filter((item) => item.tags.includes(fallback.tag) && [...required2].every((capability) => item.capabilities.includes(capability))).slice().sort((left, right) => right.priority - left.priority || left.routeId.localeCompare(right.routeId));
}
if (fallback.provider && fallback.model) {
return models.filter((item) => item.vendor === fallback.provider && item.model === fallback.model);
}
return [];
}
function buildFallbackChain(input) {
const admitted = new Set(input.admitted);
const disabled = new Set(input.disabled);
const critics = new Set(input.criticVendors ?? []);
const byId = new Map(input.models.map((model) => [model.routeId, model]));
const chain = [];
const seen = /* @__PURE__ */ new Set();
const entries = [...input.roster, ...input.extendsRoster ?? []];
const push2 = (model, effort) => {
if (!model || seen.has(model.routeId)) return;
const candidate = eligible(model, admitted, disabled, input.liveWrite);
if (!candidate) return;
if (input.vendorIndependenceRequired && chain.length > 0 && critics.has(candidate.vendor)) return;
seen.add(model.routeId);
const resolvedEffort = effort && EFFORTS2.has(effort) ? effort : void 0;
chain.push(resolvedEffort ? { ...candidate, effort: resolvedEffort } : candidate);
};
for (const entry of entries) {
const model = byId.get(entry.route);
push2(model, entry.effort);
if (!model) continue;
for (const fallback of model.fallbacks) {
for (const resolved of selectorsFor2(fallback, input.models)) push2(resolved, entry.effort);
}
}
return chain;
}
function decideRouteSwitch(input) {
if (!input.policy || input.policy.onError.length === 0) return { action: "continue", cause: "disabled" };
if (!input.failure.walkable) return { action: "continue", cause: "not_walkable" };
if (!input.policy.onError.includes(input.failure.class)) {
return { action: "continue", cause: "class_not_opted_in" };
}
if (input.switchesUsed >= input.policy.maxSwitches) return { action: "continue", cause: "budget" };
const index = input.chain.findIndex((candidate) => candidate.routeId === input.currentRouteId);
const next = index >= 0 ? input.chain[index + 1] : void 0;
if (!next) return { action: "continue", cause: "no_candidate" };
const effort = next.effort ?? (input.currentEffort && EFFORTS2.has(input.currentEffort) ? input.currentEffort : void 0);
return {
action: "switch",
to: next,
reason: input.failure.class,
...effort ? { effort } : {}
};
}
function parseSessionCarry(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
const transcript = value.transcript;
if (!Array.isArray(transcript) || transcript.length === 0) return void 0;
const messages = [];
let total = 0;
for (const item of transcript) {
if (messages.length >= MAX_CARRY_MESSAGES) break;
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
const role = item.role;
const text = item.text;
if (typeof role !== "string" || !CARRY_ROLES.has(role) || typeof text !== "string" || text.length === 0) continue;
const clipped = text.slice(0, MAX_CARRY_TEXT);
if (total + clipped.length > MAX_CARRY_TOTAL) break;
total += clipped.length;
messages.push({ role, text: clipped });
}
return messages.length > 0 ? { transcript: messages } : void 0;
}
function mergeSessionCarry(left, right) {
return parseSessionCarry({ transcript: [...left?.transcript ?? [], ...right?.transcript ?? []] });
}
function carryForwardPrompt(prompt, carry) {
if (!carry || carry.transcript.length === 0) return prompt;
const lines = carry.transcript.map((message) => `${message.role}: ${message.text}`);
const block = `Prior attempt transcript:
${lines.join("\n")}`;
if (!prompt || prompt.length === 0) return block;
return `${prompt}
${block}`;
}
function readYaml(file) {
if (!existsSync12(file)) return void 0;
try {
const parsed = (0, import_yaml8.parse)(readFileSync10(file, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
return parsed;
} catch {
return void 0;
}
}
function stringList(value) {
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function readSelectors(projectRoot, value) {
if (!Array.isArray(value)) return [];
const modelsDir = join13(projectRoot, ".kxm", "models");
const selectors = [];
for (const item of value) {
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
const record2 = item;
if (typeof record2.profile === "string") {
selectors.push({ profile: findYamlBasename(modelsDir, record2.profile, "route") ?? record2.profile });
} else if (typeof record2.tag === "string") {
selectors.push({
tag: record2.tag,
...Array.isArray(record2.capabilities) ? { capabilities: stringList(record2.capabilities) } : {}
});
} else if (typeof record2.provider === "string" && typeof record2.model === "string") {
selectors.push({ provider: record2.provider, model: record2.model });
}
}
return selectors;
}
function loadChainModel(projectRoot, routeId2, writerIds) {
const modelsDir = join13(projectRoot, ".kxm", "models");
const fileId = findYamlBasename(modelsDir, routeId2, "route") ?? routeId2;
const doc = readYaml(join13(modelsDir, `${fileId}.yaml`));
if (!doc || doc.schema !== "kxm.model.v2") return void 0;
const harness = typeof doc.harness === "string" ? doc.harness : "";
const model = typeof doc.model === "string" ? doc.model : "";
const vendor = typeof doc.vendor === "string" ? doc.vendor : "";
if (!harness || !model || !vendor) return void 0;
const permissions = stringList(doc.permissions);
const selector = [model, `${vendor}/${model}`, `${harness}/${model}`].find((candidate) => candidate.includes("/")) ?? `${vendor}/${model}`;
const parts = splitSelector(selector);
const hosted = parts ? validateHarnessModelPair(harness, { provider: parts.provider, model: parts.model }).valid : false;
return {
routeId: fileId,
harness,
model,
vendor,
status: typeof doc.status === "string" ? doc.status : "",
permissions,
tags: stringList(doc.tags),
capabilities: stringList(doc.capabilities),
priority: typeof doc.priority === "number" ? doc.priority : 0,
fallbacks: readSelectors(projectRoot, doc.fallbacks),
hosted,
writerReady: oneShotWriterArgs(harness) !== void 0,
onWriterRoster: writerIds.has(fileId) || writerIds.has(routeId2)
};
}
function canonicalRoster(projectRoot, entries) {
const modelsDir = join13(projectRoot, ".kxm", "models");
return entries.map((entry) => {
const route = findYamlBasename(modelsDir, entry.route, "route") ?? entry.route;
return entry.effort ? { route, effort: entry.effort } : { route };
});
}
function rosterEntries(doc) {
if (!Array.isArray(doc?.roster)) return [];
const entries = [];
for (const item of doc.roster) {
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
const route = item.route;
const effort = item.effort;
if (typeof route !== "string" || route.length === 0) continue;
entries.push(typeof effort === "string" ? { route, effort } : { route });
}
return entries;
}
function loadModelsFor(projectRoot, roster, writerIds) {
const modelsDir = join13(projectRoot, ".kxm", "models");
const wanted = /* @__PURE__ */ new Set();
for (const entry of roster) wanted.add(entry.route);
if (existsSync12(modelsDir)) {
for (const name of readdirSync7(modelsDir)) {
if (!name.endsWith(".yaml") || name === "inventory.yaml") continue;
wanted.add(name.slice(0, -5));
}
}
const models = [];
const seen = /* @__PURE__ */ new Set();
for (const routeId2 of wanted) {
const model = loadChainModel(projectRoot, routeId2, writerIds);
if (!model || seen.has(model.routeId)) continue;
seen.add(model.routeId);
models.push(model);
}
return models;
}
function criticVendors(projectRoot, writerIds) {
const dir = join13(projectRoot, ".kxm", "roles");
if (!existsSync12(dir)) return [];
const vendors = [];
for (const name of readdirSync7(dir)) {
if (!name.endsWith(".yaml")) continue;
const doc = readYaml(join13(dir, name));
const purpose = doc?.purpose;
if (purpose !== "reviewer-arch" && purpose !== "reviewer-cli") continue;
const first = rosterEntries(doc)[0];
if (!first) continue;
const model = loadChainModel(projectRoot, first.route, writerIds);
if (model?.status === "admitted") vendors.push(model.vendor);
}
return vendors;
}
function loadAgentFallback(projectRoot, agentId, options) {
const agentsDir = join13(projectRoot, ".kxm", "agents");
const agentFile = findYamlBasename(agentsDir, agentId, "agent") ?? agentId;
const agent = readYaml(join13(agentsDir, `${agentFile}.yaml`));
const roleId = typeof agent?.role === "string" ? agent.role : "";
if (!roleId) return void 0;
const role = readYaml(join13(projectRoot, ".kxm", "roles", `${roleId}.yaml`));
if (!role) return void 0;
const policyRecord = role.policy && typeof role.policy === "object" ? role.policy.fallback : void 0;
const policy = parseFallbackPolicy(policyRecord);
if (!policy) return void 0;
const own2 = canonicalRoster(projectRoot, rosterEntries(role));
const seenRoles = /* @__PURE__ */ new Set([roleId]);
let extendsRoster = [];
let cursor = typeof role.extends === "string" ? role.extends : "";
while (cursor && !seenRoles.has(cursor)) {
seenRoles.add(cursor);
const parent = readYaml(join13(projectRoot, ".kxm", "roles", `${cursor}.yaml`));
extendsRoster = extendsRoster.concat(canonicalRoster(projectRoot, rosterEntries(parent)));
cursor = typeof parent?.extends === "string" ? parent.extends : "";
}
const writerIds = new Set(listRoleBindings(projectRoot).writer ?? []);
const models = loadModelsFor(projectRoot, [...own2, ...extendsRoster], writerIds);
const routePolicy = loadRoutePolicy(projectRoot);
const independence = Boolean(role.policy && typeof role.policy === "object" && role.policy.vendorIndependenceRequired);
const chain = buildFallbackChain({
roster: own2,
extendsRoster,
models,
admitted: routePolicy.admitted,
disabled: routePolicy.disabled,
liveWrite: options.liveWrite,
criticVendors: independence ? criticVendors(projectRoot, writerIds) : [],
vendorIndependenceRequired: independence
});
return { policy, chain, roleId };
}
// plugins/kxm/src/worktree-witness.ts
import { spawnSync as spawnSync4 } from "node:child_process";
function gitText(cwd, args) {
const result = spawnSync4("git", ["-C", cwd, ...args], {
encoding: "utf8",
windowsHide: true,
timeout: 15e3
});
if (result.error || result.status !== 0) return void 0;
return result.stdout ?? "";
}
function repositoryHasNoCommits(cwd) {
const listed = gitText(cwd, ["rev-list", "--max-count=1", "--all"]);
return listed !== void 0 && listed.trim() === "";
}
function captureWorktreeWitness(cwd) {
const headRun = gitText(cwd, ["rev-parse", "HEAD"]);
if (headRun === void 0 && !repositoryHasNoCommits(cwd)) {
return { unwitnessed: true, fingerprint: "" };
}
const head = headRun ?? "";
const porcelain = gitText(cwd, ["status", "--porcelain=v1", "-uall"]);
const diff = gitText(cwd, ["diff", "--no-ext-diff"]);
const staged = gitText(cwd, ["diff", "--cached", "--no-ext-diff"]);
if (porcelain === void 0 || diff === void 0 || staged === void 0) {
return { unwitnessed: true, fingerprint: "" };
}
return { unwitnessed: false, fingerprint: `${head}\0${porcelain}\0${diff}\0${staged}` };
}
function worktreeChanged(before, after) {
if (before.unwitnessed || after.unwitnessed) return false;
return before.fingerprint !== after.fingerprint;
}
function applyAuthoringWitness(result, input) {
const changed = worktreeChanged(input.before, input.after);
const unwitnessed = input.before.unwitnessed || input.after.unwitnessed;
const providerMetadata = { ...result.providerMetadata ?? {} };
if (input.writes) {
if (unwitnessed || !changed) {
providerMetadata.authored = false;
providerMetadata.authoringWitness = unwitnessed ? "unwitnessed" : "unchanged";
if (result.outcome === "passed") return { ...result, outcome: "failed", providerMetadata };
} else {
providerMetadata.authored = true;
providerMetadata.authoringWitness = "changed";
}
} else {
providerMetadata.authored = false;
if (!unwitnessed && changed) {
providerMetadata.authoringWitness = "readonly_mutated";
if (result.outcome === "passed") return { ...result, outcome: "failed", providerMetadata };
} else {
providerMetadata.authoringWitness = unwitnessed ? "unwitnessed" : "read-only";
}
}
return { ...result, providerMetadata };
}
// plugins/kxm/src/context-packet.ts
import { randomUUID as randomUUID4 } from "node:crypto";
var CONTEXT_PACKET_SCHEMA = "kxm.context-packet.v2";
function buildFormalContextPacket(input) {
const packetId = `ctxpkt_${randomUUID4().replaceAll("-", "").slice(0, 16)}`;
const now = (/* @__PURE__ */ new Date()).toISOString();
const items = input.arbitratedItems ?? [];
const sharedDefaults = [];
const projectKnowledge = [];
const currentState = [];
const contradictions = [];
const activeSkills = [];
const provenanceSummary = {};
for (const item of items) {
provenanceSummary[item.kind] = (provenanceSummary[item.kind] ?? 0) + 1;
if (item.project === "_shared") {
sharedDefaults.push({ id: item.id, summary: item.summary });
} else if (item.kind === "knowledge") {
projectKnowledge.push(item);
} else if (item.kind === "state" || item.kind === "episode") {
currentState.push(item);
} else if (item.kind === "skill") {
activeSkills.push(item);
} else {
projectKnowledge.push(item);
}
}
if (input.environment) {
if (input.environment.sharedDefaults) sharedDefaults.push(...input.environment.sharedDefaults);
if (input.environment.projectKnowledge) projectKnowledge.push(...input.environment.projectKnowledge);
if (input.environment.currentState) currentState.push(...input.environment.currentState);
if (input.environment.contradictions) contradictions.push(...input.environment.contradictions);
if (input.environment.activeSkills) activeSkills.push(...input.environment.activeSkills);
}
const allocatedTokens = input.tokenBudget ?? 16e3;
const estimatedTokens = Math.ceil(
(JSON.stringify(input.task).length + JSON.stringify(input.plan).length + JSON.stringify(input.predecessors ?? []).length + JSON.stringify(items).length) / 4
);
return {
schema: CONTEXT_PACKET_SCHEMA,
packetId,
project: input.project,
generatedAt: now,
targetRole: input.targetRole,
task: input.task,
acceptanceCriteria: input.acceptanceCriteria ?? [],
plan: input.plan,
predecessors: input.predecessors ?? [],
environment: {
sharedDefaults,
projectKnowledge,
currentState,
contradictions,
activeSkills
},
budget: {
allocatedTokens,
estimatedTokens,
unresolvedGaps: [...input.unresolvedGaps ?? []],
provenanceSummary
}
};
}
function formatContextPacketForPrompt(packet) {
const sections = [];
sections.push(`# Context Packet [${packet.packetId}]`);
sections.push(`**Project:** ${packet.project} | **Role:** ${packet.targetRole} | **Step:** ${packet.task.stepId} (Attempt ${packet.task.stepAttempt})`);
sections.push(`**Permission:** ${packet.task.permissionCeiling} | **Allowed Outcomes:** ${packet.task.allowedOutcomes.join(", ")}`);
sections.push("");
sections.push(`## 1. Objective`);
sections.push(packet.task.objective);
sections.push("");
if (packet.acceptanceCriteria.length > 0) {
sections.push(`## 2. Acceptance Criteria`);
for (const c of packet.acceptanceCriteria) {
sections.push(`- [ ] **${c.id}** (${c.verificationKind}${c.required ? ", required" : ""}): ${c.description}${c.targetRef ? ` [${c.targetRef}]` : ""}`);
}
sections.push("");
}
sections.push(`## 3. Plan Pointer`);
sections.push(`Plan Hash: \`${packet.plan.planHash}\` | Step ${packet.plan.activeStepIndex + 1} of ${packet.plan.totalSteps}`);
if (packet.plan.settledDecisions.length > 0) {
sections.push(`Settled Decisions:`);
for (const d of packet.plan.settledDecisions) {
sections.push(` - ${d}`);
}
}
sections.push("");
if (packet.predecessors.length > 0) {
sections.push(`## 4. Predecessor Outputs`);
for (const p of packet.predecessors) {
sections.push(`### Predecessor: ${p.stepId} (${p.role}) - ${p.status}`);
sections.push(p.summary);
if (p.artifacts.length > 0) {
sections.push(`Artifacts:`);
for (const a of p.artifacts) {
sections.push(` - \`${a.name}\` [${a.kind}] (${a.artifactRef})`);
if (a.contentSnippet) {
sections.push(` \`\`\`
${a.contentSnippet.trim()}
\`\`\``);
}
}
}
}
sections.push("");
}
if (packet.environment.projectKnowledge.length > 0 || packet.environment.sharedDefaults.length > 0 || packet.environment.activeSkills.length > 0 || packet.environment.contradictions.length > 0) {
sections.push(`## 5. Environment & Memory`);
if (packet.environment.sharedDefaults.length > 0) {
sections.push(`### Shared Defaults`);
for (const d of packet.environment.sharedDefaults) {
sections.push(`- ${d.summary}`);
}
}
if (packet.environment.projectKnowledge.length > 0) {
sections.push(`### Project Knowledge`);
for (const k of packet.environment.projectKnowledge.slice(0, 5)) {
sections.push(`- [${k.authority}] ${k.summary}`);
}
}
if (packet.environment.activeSkills.length > 0) {
sections.push(`### Active Skills`);
for (const skill of packet.environment.activeSkills) {
sections.push(`- ${skill.summary} (${skill.provenance.sourceRef ?? skill.id})`);
}
}
if (packet.environment.contradictions.length > 0) {
sections.push(`### Active Contradictions`);
for (const c of packet.environment.contradictions) {
sections.push(`- \u26A0\uFE0F ${c.summary}`);
}
}
sections.push("");
}
return sections.join("\n").trim();
}
function estimateContextPacketTokens(packet) {
const prompt = formatContextPacketForPrompt(packet);
return Math.ceil(prompt.length / 4);
}
function pruneContextPacket(packet, tokenBudget) {
const budget = tokenBudget ?? packet.budget.allocatedTokens;
let currentTokens = estimateContextPacketTokens(packet);
const initialTokens = currentTokens;
const prunedStages = [];
const prunedItemCounts = {
sharedDefaults: 0,
episodes: 0,
docs: 0,
artifactSnippets: 0
};
const unresolvedGaps = [...packet.budget.unresolvedGaps];
if (currentTokens <= budget) {
return {
packet: {
...packet,
budget: {
...packet.budget,
allocatedTokens: budget,
estimatedTokens: currentTokens
}
},
audit: {
initialTokens,
finalTokens: currentTokens,
budgetTokens: budget,
prunedStages,
prunedItemCounts,
unresolvedGaps
}
};
}
const environment = {
sharedDefaults: [...packet.environment.sharedDefaults],
projectKnowledge: [...packet.environment.projectKnowledge],
currentState: [...packet.environment.currentState],
contradictions: [...packet.environment.contradictions],
activeSkills: [...packet.environment.activeSkills]
};
const predecessors = packet.predecessors.map((p) => ({
...p,
artifacts: p.artifacts.map((a) => ({ ...a }))
}));
const workingPacket = {
...packet,
environment,
predecessors,
budget: { ...packet.budget, allocatedTokens: budget }
};
if (environment.sharedDefaults.length > 0 && currentTokens > budget) {
prunedStages.push("L1_defaults");
while (environment.sharedDefaults.length > 0 && currentTokens > budget) {
environment.sharedDefaults.pop();
prunedItemCounts.sharedDefaults += 1;
currentTokens = estimateContextPacketTokens(workingPacket);
}
}
if (currentTokens > budget) {
const episodeIndices = [];
for (let i = environment.currentState.length - 1; i >= 0; i--) {
if (environment.currentState[i]?.kind === "episode") {
episodeIndices.push(i);
}
}
if (episodeIndices.length > 0) {
prunedStages.push("L2_episodes");
for (const idx of episodeIndices) {
if (currentTokens <= budget) break;
environment.currentState.splice(idx, 1);
prunedItemCounts.episodes += 1;
currentTokens = estimateContextPacketTokens(workingPacket);
}
}
}
if (currentTokens > budget && environment.projectKnowledge.length > 0) {
prunedStages.push("L2_docs");
while (environment.projectKnowledge.length > 0 && currentTokens > budget) {
environment.projectKnowledge.pop();
prunedItemCounts.docs += 1;
currentTokens = estimateContextPacketTokens(workingPacket);
}
}
if (currentTokens > budget) {
const hasArtifacts = predecessors.some((p) => p.artifacts.length > 0);
if (hasArtifacts) {
prunedStages.push("L5_artifacts");
for (const p of predecessors) {
for (const a of p.artifacts) {
if (a.contentSnippet) {
a.contentSnippet = void 0;
prunedItemCounts.artifactSnippets += 1;
}
}
}
currentTokens = estimateContextPacketTokens(workingPacket);
if (currentTokens > budget) {
for (const p of predecessors) {
p.artifacts = [];
}
currentTokens = estimateContextPacketTokens(workingPacket);
}
}
}
if (currentTokens > budget) {
unresolvedGaps.push("context_budget_exceeded_task_inviolable");
}
workingPacket.budget = {
...packet.budget,
allocatedTokens: budget,
estimatedTokens: currentTokens,
unresolvedGaps
};
return {
packet: workingPacket,
audit: {
initialTokens,
finalTokens: currentTokens,
budgetTokens: budget,
prunedStages,
prunedItemCounts,
unresolvedGaps
}
};
}
// plugins/kxm/src/dispatch-context.ts
import { spawnSync as spawnSync5 } from "node:child_process";
import { readdirSync as readdirSync10 } from "node:fs";
import { extname as extname3, join as join16 } from "node:path";
// plugins/kxm/src/protocol.ts
var DEFAULT_MESSAGE_TTL_MS = 24 * 60 * 6e4;
var MAX_MESSAGE_TTL_MS = 7 * 24 * 60 * 6e4;
var DEFAULT_MESSAGE_RETENTION_MS = 7 * 24 * 60 * 6e4;
var MAX_BODY_BYTES = 256 * 1024;
var MAX_AGENT_HOST_CHARS = 64;
var MAX_LEASE_TTL_MS = 10 * 6e4;
var DEFAULT_LEASE_TTL_MS = 5 * 6e4;
var ProtocolError = class extends Error {
statusCode;
code;
extras;
constructor(statusCode, message, code = "protocol_error", extras) {
super(message);
this.name = "ProtocolError";
this.statusCode = statusCode;
this.code = code;
if (extras) this.extras = extras;
}
};
function nowIso() {
return (/* @__PURE__ */ new Date()).toISOString();
}
function requireString(value, field, options = {}) {
if (typeof value !== "string") {
throw new ProtocolError(400, `${field} must be a string`);
}
const result = value.trim();
if (!options.allowEmpty && result.length === 0) {
throw new ProtocolError(400, `${field} cannot be empty`);
}
if (options.max !== void 0 && result.length > options.max) {
throw new ProtocolError(400, `${field} exceeds ${options.max} characters`);
}
return result;
}
// plugins/kxm/src/context.ts
var MAX_CONTEXT_SUMMARY_CHARS = 4e3;
var MAX_CONTEXT_ID_REFS = 64;
var MAX_CONTEXT_ITEMS = 256;
var MIN_CONTEXT_BUDGET_TOKENS = 512;
var MAX_CONTEXT_BUDGET_TOKENS = 2e5;
var DEFAULT_CONTEXT_BUDGET_TOKENS = 32e3;
var MAX_CONTEXT_ROLE_CHARS = 64;
var MAX_CONTEXT_TASK_CHARS = 2e3;
var AUTHORITY_GRANT_FLOOR = {
human: "policy",
workflow: "policy",
git: "instruction",
peer: "evidence",
tool: "evidence",
external: "evidence",
derived: "evidence"
};
function authorityGrantFloor(sourceType) {
return AUTHORITY_GRANT_FLOOR[sourceType];
}
var RESERVED_CONTROL_PLANE_FIELDS = /* @__PURE__ */ new Set([
"permissions",
"tools",
"allow",
"deny",
"grants",
"approval",
"policy",
"scopes",
"credentials",
"secrets",
"token",
"apiKey",
"password"
]);
var CONTEXT_ITEM_KINDS = ["evidence", "state", "episode", "knowledge", "skill"];
var CONTEXT_SOURCE_TYPES = [
"human",
"git",
"workflow",
"tool",
"peer",
"external",
"derived"
];
var CONTEXT_AUTHORITIES = ["policy", "instruction", "evidence", "hypothesis"];
var CONTEXT_CONFIDENCES = ["verified", "probable", "uncertain"];
var CONTEXT_SCOPES = ["agent", "project", "run", "operator"];
var CONTEXT_ROLES = ["repro", "planner", "critic", "implementer", "verifier"];
function oneOf(value, field, allowed) {
if (typeof value !== "string" || !allowed.includes(value)) {
throw new ProtocolError(400, `${field} must be one of ${allowed.join(", ")}`, "invalid_context_field");
}
return value;
}
function idRefs(value, field, required2 = false) {
if (value === void 0 || value === null) return required2 ? [] : void 0;
if (!Array.isArray(value)) {
throw new ProtocolError(400, `${field} must be an array of identifiers`, "invalid_context_field");
}
if (value.length > MAX_CONTEXT_ID_REFS) {
throw new ProtocolError(
400,
`${field} exceeds ${MAX_CONTEXT_ID_REFS} references`,
"context_limits_exceeded"
);
}
const seen = /* @__PURE__ */ new Set();
const refs = [];
for (const candidate of value) {
if (typeof candidate !== "string" || !candidate.trim()) {
throw new ProtocolError(400, `${field} must contain non-empty identifiers`, "invalid_context_field");
}
const ref = candidate.trim();
if (seen.has(ref)) {
throw new ProtocolError(400, `${field} contains duplicate reference ${ref}`, "invalid_context_field");
}
seen.add(ref);
refs.push(ref);
}
return refs;
}
function optionalIsoTimestamp(value, field) {
if (value === void 0 || value === null) return void 0;
if (typeof value !== "string" || !Number.isFinite(Date.parse(value))) {
throw new ProtocolError(400, `${field} must be an ISO-8601 timestamp`, "invalid_context_field");
}
return value;
}
function parseContextItem(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new ProtocolError(400, "context item must be an object", "invalid_context_item");
}
const input = value;
for (const field of Object.keys(input)) {
if (RESERVED_CONTROL_PLANE_FIELDS.has(field)) {
throw new ProtocolError(
403,
`context items may not carry control-plane field "${field}"`,
"context_authority_violation"
);
}
}
const item = {
id: requireString(input.id, "context item id", { max: 128 }),
kind: oneOf(input.kind, "context item kind", CONTEXT_ITEM_KINDS),
project: requireString(input.project, "context item project", { max: 200 }),
summary: redactSecrets(requireString(input.summary, "context item summary", { max: MAX_CONTEXT_SUMMARY_CHARS })),
provenance: parseContextProvenance(input.provenance),
authority: oneOf(input.authority, "context item authority", CONTEXT_AUTHORITIES),
confidence: oneOf(input.confidence, "context item confidence", CONTEXT_CONFIDENCES)
};
if (input.scope !== void 0 && input.scope !== null) {
item.scope = oneOf(input.scope, "context item scope", CONTEXT_SCOPES);
}
const observedAt = optionalIsoTimestamp(input.observedAt, "context item observedAt");
const validFrom = optionalIsoTimestamp(input.validFrom, "context item validFrom");
const validUntil = optionalIsoTimestamp(input.validUntil, "context item validUntil");
if (observedAt !== void 0) item.observedAt = observedAt;
if (validFrom !== void 0) item.validFrom = validFrom;
if (validUntil !== void 0) item.validUntil = validUntil;
if (input.status !== void 0 && input.status !== null) {
item.status = oneOf(input.status, "context item status", ["current", "superseded", "proposed", "rejected"]);
}
const supersedes = idRefs(input.supersedes, "context item supersedes");
if (supersedes !== void 0) {
if (supersedes.includes(item.id)) {
throw new ProtocolError(400, "context item cannot supersede itself", "invalid_context_item");
}
item.supersedes = supersedes;
}
const evidenceRefs = idRefs(input.evidenceRefs, "context item evidenceRefs");
if (evidenceRefs !== void 0) item.evidenceRefs = evidenceRefs;
const stateKey = input.stateKey === void 0 || input.stateKey === null ? void 0 : requireString(input.stateKey, "context item stateKey", { max: 200 });
if (stateKey !== void 0) item.stateKey = stateKey;
if (item.kind === "state" && item.stateKey === void 0) {
throw new ProtocolError(400, "state items require a stateKey", "invalid_context_item");
}
if (item.kind === "state" && item.status === void 0) {
throw new ProtocolError(400, "state items require an explicit lifecycle status", "invalid_context_item");
}
const grantFloor = authorityRank(authorityGrantFloor(item.provenance.sourceType));
if (authorityRank(item.authority) > grantFloor) {
throw new ProtocolError(
403,
`content of origin ${item.provenance.sourceType} cannot claim ${item.authority} authority`,
"context_authority_violation"
);
}
return item;
}
function parseContextProvenance(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new ProtocolError(400, "context provenance must be an object", "invalid_context_item");
}
const input = value;
const provenance = {
sourceType: oneOf(input.sourceType, "context provenance sourceType", CONTEXT_SOURCE_TYPES)
};
const sourceRef = input.sourceRef === void 0 || input.sourceRef === null ? void 0 : requireString(input.sourceRef, "context provenance sourceRef", { max: 512 });
if (sourceRef !== void 0) provenance.sourceRef = redactSecrets(sourceRef);
const derivedFrom = idRefs(input.derivedFrom, "context provenance derivedFrom");
if (derivedFrom !== void 0) provenance.derivedFrom = derivedFrom;
return provenance;
}
function parseContextRequest(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new ProtocolError(400, "context request must be an object", "invalid_context_request");
}
const input = value;
const request = {
project: requireString(input.project, "context request project", { max: 200 }),
role: requireString(input.role, "context request role", { max: MAX_CONTEXT_ROLE_CHARS }),
task: requireString(input.task, "context request task", { max: MAX_CONTEXT_TASK_CHARS })
};
const workflowRunId = input.workflowRunId === void 0 || input.workflowRunId === null ? void 0 : requireString(input.workflowRunId, "context request workflowRunId", { max: 128 });
if (workflowRunId !== void 0) request.workflowRunId = workflowRunId;
const stageId = input.stageId === void 0 || input.stageId === null ? void 0 : requireString(input.stageId, "context request stageId", { max: 128 });
if (stageId !== void 0) request.stageId = stageId;
if (input.budgetTokens !== void 0 && input.budgetTokens !== null) {
const budget = input.budgetTokens;
if (!Number.isInteger(budget) || budget < MIN_CONTEXT_BUDGET_TOKENS || budget > MAX_CONTEXT_BUDGET_TOKENS) {
throw new ProtocolError(
400,
`context request budgetTokens must be an integer between ${MIN_CONTEXT_BUDGET_TOKENS} and ${MAX_CONTEXT_BUDGET_TOKENS}`,
"invalid_context_request"
);
}
request.budgetTokens = budget;
}
if (input.includeKinds !== void 0 && input.includeKinds !== null) {
if (!Array.isArray(input.includeKinds) || input.includeKinds.length < 1 || input.includeKinds.length > CONTEXT_ITEM_KINDS.length) {
throw new ProtocolError(
400,
"context request includeKinds must be a non-empty array of item kinds",
"invalid_context_request"
);
}
request.includeKinds = input.includeKinds.map((kind) => oneOf(kind, "context request includeKinds", CONTEXT_ITEM_KINDS));
}
return request;
}
function validateContextPacketContents(request, packet) {
const items = [
...packet.currentState,
...packet.knowledge,
...packet.evidence,
...packet.episodes,
...packet.skills,
...packet.contradictions
];
if (items.length > MAX_CONTEXT_ITEMS) {
throw new ProtocolError(400, `context packet exceeds ${MAX_CONTEXT_ITEMS} items`, "context_limits_exceeded");
}
const allowed = request.includeKinds ? new Set(request.includeKinds) : void 0;
for (const item of items) {
if (item.project !== request.project && item.project !== "_shared") {
throw new ProtocolError(
400,
`context packet contains cross-project item ${item.id}`,
"context_isolation_violation"
);
}
if (allowed && !allowed.has(item.kind)) {
throw new ProtocolError(
400,
`context packet contains item ${item.id} of unrequested kind ${item.kind}`,
"context_isolation_violation"
);
}
}
}
function contextItemCharacters(item) {
return item.summary.length + item.id.length + item.kind.length + (item.provenance.sourceRef?.length ?? 0);
}
function estimateContextTokens(items) {
let characters = 0;
for (const item of items) characters += contextItemCharacters(item);
return Math.ceil(characters / 4);
}
function authorityRank(authority) {
switch (authority) {
case "policy":
return 3;
case "instruction":
return 2;
case "evidence":
return 1;
case "hypothesis":
return 0;
}
}
function provenanceSummaryOf(items) {
const summary = {};
for (const item of items) {
summary[item.provenance.sourceType] = (summary[item.provenance.sourceType] ?? 0) + 1;
}
for (const key of Object.keys(summary).sort()) {
if (summary[key] === 0) delete summary[key];
}
return summary;
}
// plugins/kxm/src/relevance.ts
var RELEVANCE_STOPWORDS = Object.freeze(/* @__PURE__ */ new Set([
"a",
"an",
"and",
"are",
"as",
"at",
"be",
"been",
"but",
"by",
"can",
"could",
"did",
"do",
"does",
"for",
"from",
"had",
"has",
"have",
"how",
"if",
"in",
"into",
"is",
"it",
"its",
"of",
"on",
"or",
"our",
"should",
"so",
"than",
"that",
"the",
"their",
"them",
"then",
"there",
"these",
"they",
"this",
"those",
"to",
"was",
"we",
"were",
"what",
"when",
"where",
"which",
"while",
"who",
"why",
"will",
"with",
"would",
"you",
"your"
]));
var RELEVANCE_K1 = 1.2;
var RELEVANCE_B = 0.75;
var MIN_TOKEN_CHARS = 2;
var MAX_TOKEN_CHARS = 64;
function foldPlural(token) {
if (new RegExp("^\\p{N}+$", "u").test(token)) return token;
if (token.length > 4 && token.endsWith("ies")) return `${token.slice(0, -3)}y`;
if (token.length > 4 && token.endsWith("sses")) return token.slice(0, -2);
if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us") && !token.endsWith("is")) {
return token.slice(0, -1);
}
return token;
}
function relevanceTokens(text) {
const tokens = [];
for (const raw of text.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
if (raw.length < MIN_TOKEN_CHARS || raw.length > MAX_TOKEN_CHARS) continue;
if (RELEVANCE_STOPWORDS.has(raw)) continue;
tokens.push(foldPlural(raw));
}
return tokens;
}
function scoreRelevance(query, documents) {
const scores = documents.map(() => 0);
const terms = [...new Set(relevanceTokens(query))];
if (terms.length === 0 || documents.length === 0) return scores;
const indexed = documents.map((document) => {
const tokens = relevanceTokens(document);
const frequencies = /* @__PURE__ */ new Map();
for (const token of tokens) frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
return { length: tokens.length, frequencies };
});
const count = indexed.length;
let totalLength = 0;
for (const document of indexed) totalLength += document.length;
const averageLength = totalLength > 0 ? totalLength / count : 1;
const inverseFrequency = /* @__PURE__ */ new Map();
for (const term of terms) {
let documentFrequency = 0;
for (const document of indexed) {
if (document.frequencies.has(term)) documentFrequency += 1;
}
inverseFrequency.set(term, Math.log(1 + (count - documentFrequency + 0.5) / (documentFrequency + 0.5)));
}
indexed.forEach((document, index) => {
let score = 0;
for (const term of terms) {
const frequency = document.frequencies.get(term) ?? 0;
if (frequency === 0) continue;
const lengthNorm = 1 - RELEVANCE_B + RELEVANCE_B * (document.length / averageLength);
score += inverseFrequency.get(term) * (frequency * (RELEVANCE_K1 + 1) / (frequency + RELEVANCE_K1 * lengthNorm));
}
scores[index] = score;
});
return scores;
}
function roundRelevance(score) {
return Math.round(score * 1e3) / 1e3;
}
function contextItemRelevanceText(item) {
return item.stateKey !== void 0 ? `${item.summary} ${item.stateKey}` : item.summary;
}
function compareCodeUnitIds(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
// plugins/kxm/src/arbiter.ts
var ROLE_POLICIES = [
{
role: "repro",
label: "Reproduction specialist",
kinds: ["episode", "knowledge", "evidence"],
journalCategories: ["error", "lesson", "observation", "contradiction"],
budgetTokens: 8e3
},
{
role: "planner",
label: "Planner",
kinds: ["state", "knowledge", "evidence"],
journalCategories: ["plan", "decision", "contradiction", "observation", "hypothesis", "experiment"],
budgetTokens: 16e3
},
{
role: "critic",
label: "Independent critic",
kinds: ["knowledge", "evidence", "episode"],
journalCategories: ["contradiction", "error", "lesson", "experiment"],
budgetTokens: 12e3
},
{
role: "implementer",
label: "Implementer",
kinds: ["knowledge", "state", "skill", "episode", "evidence"],
journalCategories: ["plan", "decision", "lesson", "state-change"],
budgetTokens: 16e3
},
{
role: "verifier",
label: "Verifier",
kinds: ["evidence", "knowledge", "episode"],
journalCategories: ["plan", "error", "lesson", "contradiction"],
budgetTokens: 8e3
}
];
function rolePolicy(role) {
return ROLE_POLICIES.find((policy) => policy.role === role) ?? {
role,
label: role,
kinds: ["knowledge", "evidence"],
journalCategories: ["lesson", "observation"],
budgetTokens: DEFAULT_CONTEXT_BUDGET_TOKENS
};
}
var CONFIDENCE_RANK = { verified: 3, probable: 2, uncertain: 1 };
var AUTHORITY_WEIGHT = { policy: 3, instruction: 2, evidence: 1, hypothesis: 0 };
function arbitrate(requestInput, pool, options = {}) {
const request = parseContextRequest(requestInput);
const policy = rolePolicy(request.role);
const budget = request.budgetTokens ?? policy.budgetTokens;
const contradictions = new Set(options.contradictionIds ?? []);
const candidates = [];
let excludedSuperseded = 0;
for (const candidate of pool) {
if (candidate.project !== request.project && candidate.project !== "_shared") {
throw new ProtocolError(
403,
`context pool contains cross-project item ${candidate.id}`,
"context_isolation_violation"
);
}
if (candidate.status === "superseded" || candidate.status === "rejected") {
excludedSuperseded += 1;
continue;
}
candidates.push(candidate);
}
if (options.skillLifecycle) {
for (const metadata of options.skillLifecycle.list("promoted")) {
try {
options.skillLifecycle.verify("promoted", metadata.id);
candidates.push(parseContextItem({
id: `skill_${metadata.id}`,
kind: "skill",
project: request.project,
summary: metadata.description ? `${metadata.name}: ${metadata.description}` : metadata.name,
provenance: {
sourceType: "git",
sourceRef: `skill:${metadata.id}@${metadata.contentSha256}`
},
authority: "instruction",
confidence: "verified",
status: "current"
}));
} catch {
}
}
}
const kindRank = /* @__PURE__ */ new Map();
const requestedKinds = request.includeKinds ?? policy.kinds;
requestedKinds.forEach((kind, index) => kindRank.set(kind, index));
const kindPreference = (item) => {
const rank = kindRank.get(item.kind);
return rank === void 0 ? requestedKinds.length : rank;
};
const allowedKinds = new Set(requestedKinds);
const inertProposal = (item) => item.kind === "state" && item.status !== void 0 && item.status !== "current" || item.kind === "skill" && item.status === "proposed";
const eligible2 = candidates.filter((item) => contradictions.has(item.id) || allowedKinds.has(item.kind) && !inertProposal(item));
const scoreList = scoreRelevance(request.task, eligible2.map(contextItemRelevanceText));
const scores = /* @__PURE__ */ new Map();
eligible2.forEach((item, index) => scores.set(item, scoreList[index] ?? 0));
const scoreOf = (item) => scores.get(item) ?? 0;
const when = (item) => {
const parsed = Date.parse(item.observedAt ?? item.validFrom ?? "");
return Number.isFinite(parsed) ? parsed : 0;
};
const ordered = [...eligible2].sort(
(left, right) => (contradictions.has(right.id) ? 1 : 0) - (contradictions.has(left.id) ? 1 : 0) || (left.project === request.project ? 0 : 1) - (right.project === request.project ? 0 : 1) || (scoreOf(right) > 0 ? 1 : 0) - (scoreOf(left) > 0 ? 1 : 0) || kindPreference(left) - kindPreference(right) || scoreOf(right) - scoreOf(left) || CONFIDENCE_RANK[right.confidence] - CONFIDENCE_RANK[left.confidence] || AUTHORITY_WEIGHT[right.authority] - AUTHORITY_WEIGHT[left.authority] || when(right) - when(left) || compareCodeUnitIds(left.id, right.id)
);
const selected = [];
const unresolvedGaps = [];
let characters = 0;
let deferredForBudget = 0;
for (const item of ordered) {
if (selected.length >= MAX_CONTEXT_ITEMS) {
unresolvedGaps.push("context item limit reached; refine the task or kinds");
break;
}
const itemCharacters = contextItemCharacters(item);
if (Math.ceil((characters + itemCharacters) / 4) > budget) {
deferredForBudget += 1;
continue;
}
characters += itemCharacters;
selected.push(item);
}
if (deferredForBudget > 0) {
unresolvedGaps.push(selected.length === 0 ? `budget of ${budget} tokens cannot fit any selected context` : `budget of ${budget} tokens reached; ${deferredForBudget} candidates deferred`);
}
if (candidates.length === 0) {
unresolvedGaps.push("no context records exist for this project yet");
}
const bySection = (kind) => selected.filter((item) => item.kind === kind && !contradictions.has(item.id));
const packet = {
workingState: options.workingState ?? {},
currentState: bySection("state").filter((item) => item.status === "current" || item.status === void 0),
knowledge: bySection("knowledge"),
evidence: bySection("evidence"),
episodes: bySection("episode"),
skills: bySection("skill").filter((item) => item.status !== "proposed"),
contradictions: selected.filter((item) => contradictions.has(item.id)),
unresolvedGaps,
provenanceSummary: provenanceSummaryOf(selected),
estimatedTokens: estimateContextTokens(selected)
};
validateContextPacketContents(request, packet);
return {
packet,
audit: {
request: {
project: request.project,
role: request.role,
task: request.task,
...request.workflowRunId !== void 0 ? { workflowRunId: request.workflowRunId } : {},
...request.stageId !== void 0 ? { stageId: request.stageId } : {}
},
selectedIds: selected.map((item) => item.id),
provenanceSummary: packet.provenanceSummary,
estimatedTokens: packet.estimatedTokens,
budgetTokens: budget,
candidateCount: candidates.length,
excludedSuperseded,
unresolvedGaps,
relevance: {
taskTokens: new Set(relevanceTokens(request.task)).size,
matchedCandidates: scoreList.filter((score) => score > 0).length,
selected: selected.map((item) => roundRelevance(scoreOf(item)))
}
}
};
}
function memoryRecordToContextItem(record2, project) {
let authority = "instruction";
if (record2.authority === "evidence") {
authority = "evidence";
}
const sourceType = CONTEXT_SOURCE_TYPES.includes(record2.provenance?.sourceType) ? record2.provenance.sourceType : "git";
const targetProject = record2.scope === "operator" ? "_shared" : project;
return parseContextItem({
id: `mem_${record2.id}`,
kind: "knowledge",
scope: record2.scope,
project: targetProject,
summary: record2.summary,
provenance: {
sourceType,
sourceRef: record2.provenance?.sourceRef ?? `memory:${record2.id}.md`
},
authority,
confidence: record2.confidence,
status: record2.lifecycle === "active" ? "current" : "superseded",
evidenceRefs: record2.evidenceRefs && record2.evidenceRefs.length > 0 ? record2.evidenceRefs : void 0
});
}
// plugins/kxm/src/memory.ts
var import_yaml9 = __toESM(require_dist(), 1);
import { existsSync as existsSync13, mkdirSync as mkdirSync5, readdirSync as readdirSync8, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "node:fs";
import { extname as extname2, join as join14, resolve as resolve8 } from "node:path";
var MEMORY_SCHEMA = "kxm.memory.v1";
var VALID_SCOPES = /* @__PURE__ */ new Set(["agent", "project", "run", "operator"]);
var VALID_AUTHORITIES = /* @__PURE__ */ new Set(["instruction", "evidence", "promoted"]);
var VALID_CONFIDENCES = /* @__PURE__ */ new Set(["verified", "probable", "uncertain"]);
var VALID_LIFECYCLES = /* @__PURE__ */ new Set(["active", "deprecated", "superseded"]);
var BANNED_CONTROL_PLANE_FIELDS = /* @__PURE__ */ new Set([
"permissions",
"tools",
"allow",
"deny",
"grants",
"approval",
"policy",
"scopes",
"credentials",
"secrets",
"token",
"apiKey",
"password"
]);
function parseFrontmatter(content) {
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) {
throw new Error("memory file must contain YAML frontmatter enclosed in '---'");
}
return { frontmatter: match[1] ?? "", body: match[2]?.trim() ?? "" };
}
function parseMemoryRecord(raw, filename = "memory.md") {
const { frontmatter, body } = parseFrontmatter(raw);
const data = (0, import_yaml9.parse)(frontmatter);
if (!data || typeof data !== "object" || Array.isArray(data)) {
throw new Error(`invalid YAML frontmatter in ${filename}`);
}
for (const field of BANNED_CONTROL_PLANE_FIELDS) {
if (field in data) {
throw new Error(`memory record ${filename} may not carry control-plane field '${field}'`);
}
}
if (data.schema !== MEMORY_SCHEMA) {
throw new Error(`memory record ${filename} has unsupported schema: expected ${MEMORY_SCHEMA}, got ${String(data.schema)}`);
}
const id = typeof data.id === "string" ? data.id.trim() : "";
if (!id || !/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/i.test(id)) {
throw new Error(`memory record ${filename} has invalid id: ${String(data.id)}`);
}
const scope = data.scope;
if (!VALID_SCOPES.has(scope)) {
throw new Error(`memory record ${filename} has invalid scope: must be one of agent, project, run, operator`);
}
const kind = typeof data.kind === "string" ? data.kind.trim() : "";
if (!kind) {
throw new Error(`memory record ${filename} is missing kind`);
}
const rawSummary = typeof data.summary === "string" ? data.summary.trim() : "";
if (!rawSummary) {
throw new Error(`memory record ${filename} is missing summary`);
}
const summary = redactSecrets(rawSummary);
const rawProv = data.provenance;
if (!rawProv || typeof rawProv !== "object" || typeof rawProv.sourceType !== "string" || !rawProv.sourceType.trim()) {
throw new Error(`memory record ${filename} is missing provenance.sourceType`);
}
const provenance = {
sourceType: rawProv.sourceType.trim(),
...typeof rawProv.sourceRef === "string" ? { sourceRef: redactSecrets(rawProv.sourceRef.trim()) } : {},
...typeof rawProv.runId === "string" ? { runId: rawProv.runId.trim() } : {},
...typeof rawProv.timestamp === "string" ? { timestamp: rawProv.timestamp.trim() } : {}
};
const authority = data.authority;
if (!VALID_AUTHORITIES.has(authority)) {
throw new Error(`memory record ${filename} has invalid authority: ${String(data.authority)}`);
}
const confidence = data.confidence;
if (!VALID_CONFIDENCES.has(confidence)) {
throw new Error(`memory record ${filename} has invalid confidence: ${String(data.confidence)}`);
}
const lifecycle = data.lifecycle;
if (!VALID_LIFECYCLES.has(lifecycle)) {
throw new Error(`memory record ${filename} has invalid lifecycle: ${String(data.lifecycle)}`);
}
const rawRefs = Array.isArray(data.evidenceRefs) ? data.evidenceRefs : [];
const evidenceRefs = rawRefs.map(String);
return {
schema: MEMORY_SCHEMA,
id,
scope,
kind,
summary,
provenance,
authority,
confidence,
lifecycle,
evidenceRefs,
...body ? { body } : {}
};
}
function memoryDirectories(repoRoot) {
const root = resolve8(repoRoot);
const memoryDir = join14(root, ".kxm", "memory");
const candidatesDir = join14(memoryDir, "candidates");
return { memoryDir, candidatesDir };
}
function loadAuthoredMemory(repoRoot) {
const { memoryDir } = memoryDirectories(repoRoot);
if (!existsSync13(memoryDir)) return [];
const records = [];
const entries = readdirSync8(memoryDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile() && extname2(entry.name) === ".md") {
const fullPath = join14(memoryDir, entry.name);
try {
const text = readFileSync11(fullPath, "utf8");
const record2 = parseMemoryRecord(text, entry.name);
if (record2.lifecycle === "active") {
records.push(record2);
}
} catch (error) {
throw new Error(`failed to parse authored memory file ${entry.name}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
return records.sort((left, right) => left.id.localeCompare(right.id));
}
// plugins/kxm/src/skills.ts
var import_yaml10 = __toESM(require_dist(), 1);
import { createHash as createHash12 } from "node:crypto";
import { existsSync as existsSync14, mkdirSync as mkdirSync6, readdirSync as readdirSync9, readFileSync as readFileSync12, renameSync, rmSync, statSync as statSync3, writeFileSync as writeFileSync7 } from "node:fs";
import { dirname as dirname8, join as join15 } from "node:path";
var SKILL_CANDIDATE_SCHEMA = "kxm.skill-candidate.v1";
var SKILL_EVALUATION_SCHEMA = "kxm.skill-evaluation.v1";
var SKILL_DECISION_SCHEMA = "kxm.skill-decision.v1";
var MAX_SKILL_NAME_CHARS = 64;
var MAX_SKILL_CONTENT_CHARS = 32e3;
var MAX_SKILL_EVIDENCE_REFS = 32;
var MAX_SKILL_MODELS = 16;
var PROMOTION_REQUIRED_EVALUATIONS = [
"static-review",
"sandbox",
"functional",
"safety"
];
var SkillLifecycleError = class extends Error {
code;
constructor(code, message) {
super(message);
this.name = "SkillLifecycleError";
this.code = code;
}
};
function skillContentSha256(content) {
return createHash12("sha256").update(content, "utf8").digest("hex");
}
function skillIdFor(name, contentSha256) {
const slug = name.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
if (!slug) throw new SkillLifecycleError("invalid_skill_name", "skill name must contain alphanumeric characters");
return `${slug}.${contentSha256.slice(0, 12)}`;
}
function parseSkillFrontmatter(content) {
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) {
return { frontmatter: null, body: content };
}
const rawFm = match[1];
const rawBody = match[2];
if (rawFm === void 0 || rawBody === void 0) {
return { frontmatter: null, body: content };
}
try {
const parsed = (0, import_yaml10.parse)(rawFm);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return { frontmatter: parsed, body: rawBody };
}
} catch {
}
return { frontmatter: null, body: content };
}
function ensureSkillFrontmatter(content, name, description) {
const parsed = parseSkillFrontmatter(content);
if (parsed.frontmatter) {
const fmName = typeof parsed.frontmatter.name === "string" && parsed.frontmatter.name.trim() ? parsed.frontmatter.name.trim() : name;
const fmDesc = typeof parsed.frontmatter.description === "string" && parsed.frontmatter.description.trim() ? parsed.frontmatter.description.trim() : description || `Governed skill for ${fmName}`;
const rest2 = parsed.body.replace(/^(\r?\n)+/, "");
return `---
name: ${fmName}
description: ${fmDesc}
---
${rest2}`;
}
const desc = description || `Governed skill for ${name}`;
const rest = content.replace(/^(\r?\n)+/, "");
return `---
name: ${name}
description: ${desc}
---
${rest}`;
}
function createUnifiedPatch(relativePath, content) {
const lines = content.split("\n");
const count = lines.length;
const header = [
`diff --git a/${relativePath} b/${relativePath}`,
"new file mode 100644",
"--- /dev/null",
`+++ b/${relativePath}`,
`@@ -0,0 +1,${count} @@`
];
const body = lines.map((l) => `+${l}`);
return [...header, ...body, ""].join("\n");
}
var SkillLifecycle = class {
root;
now;
allowOptimizationEvals;
dryRun;
/** What a `dryRun` lifecycle would have written or moved, in order. */
planned = [];
constructor(root, options = {}) {
this.root = root;
this.now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
this.allowOptimizationEvals = options.allowOptimizationEvals === true;
this.dryRun = options.dryRun === true;
}
write(file, content) {
if (this.dryRun) {
this.planned.push({ action: "write", target: file });
return;
}
mkdirSync6(dirname8(file), { recursive: true });
writeFileSync7(file, content);
}
dir(state) {
return join15(this.root, state === "candidate" ? "candidates" : `${state}s`.replace("rejecteds", "rejected").replace("promoteds", "promoted"));
}
historyFile(id) {
return join15(this.root, "history", `${id}.jsonl`);
}
paths(state, id) {
const dir = join15(this.dir(state), id);
return { dir, metadata: join15(dir, "metadata.json"), skill: join15(dir, "SKILL.md") };
}
appendHistory(id, record2) {
const line = `${JSON.stringify(record2)}
`;
if (existsSync14(this.historyFile(id))) {
const existing = readFileSync12(this.historyFile(id), "utf8");
const lines = existing.split("\n").filter((entry) => entry.trim());
this.write(this.historyFile(id), [...lines.slice(-499), line.trim()].join("\n") + "\n");
} else {
this.write(this.historyFile(id), line);
}
}
history(id) {
const file = this.historyFile(id);
if (!existsSync14(file)) return [];
return readFileSync12(file, "utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
}
readMetadata(state, id) {
const { metadata } = this.paths(state, id);
if (!existsSync14(metadata)) {
throw new SkillLifecycleError("skill_not_found", `skill ${id} not found in ${state}`);
}
return JSON.parse(readFileSync12(metadata, "utf8"));
}
move(from, to, id) {
const fromDir = join15(this.dir(from), id);
const toDir = join15(this.dir(to), id);
if (!existsSync14(fromDir)) {
throw new SkillLifecycleError("skill_not_found", `skill ${id} not found in ${from}`);
}
if (this.dryRun) {
this.planned.push({ action: "move", target: `${fromDir} -> ${toDir}` });
return;
}
mkdirSync6(this.dir(to), { recursive: true });
if (existsSync14(toDir)) rmSync(toDir, { recursive: true, force: true });
renameSync(fromDir, toDir);
}
/** Submit a new skill candidate. Content is redacted of secret material at
* creation; the ID is derived from name + content hash. */
create(input) {
const name = input.name?.trim();
if (!name || name.length > MAX_SKILL_NAME_CHARS) {
throw new SkillLifecycleError("invalid_skill_name", `skill name must be 1-${MAX_SKILL_NAME_CHARS} characters`);
}
const rawContent = redactSecrets(input.content ?? "");
if (!rawContent.trim() || rawContent.length > MAX_SKILL_CONTENT_CHARS) {
throw new SkillLifecycleError("invalid_skill_content", `skill content must be 1-${MAX_SKILL_CONTENT_CHARS} characters`);
}
const rawDesc = redactSecrets(input.description?.trim() ?? "");
const content = ensureSkillFrontmatter(rawContent, name, rawDesc);
if (content.length > MAX_SKILL_CONTENT_CHARS) {
throw new SkillLifecycleError("invalid_skill_content", `skill content must be 1-${MAX_SKILL_CONTENT_CHARS} characters`);
}
const { frontmatter } = parseSkillFrontmatter(content);
const description = typeof frontmatter?.description === "string" && frontmatter.description.trim() ? frontmatter.description.trim() : rawDesc || `Governed skill for ${name}`;
const sources = {
runIds: boundedList(input.sources?.runIds, "runIds"),
journalEntryIds: boundedList(input.sources?.journalEntryIds, "journalEntryIds"),
evidenceReceipts: boundedList(input.sources?.evidenceReceipts, "evidenceReceipts")
};
if (sources.runIds.length === 0 && sources.journalEntryIds.length === 0 && sources.evidenceReceipts.length === 0) {
throw new SkillLifecycleError(
"skill_sources_required",
"a skill candidate must reference at least one source run, journal entry, or evidence receipt"
);
}
const createdBy = input.createdBy?.trim();
if (!createdBy) throw new SkillLifecycleError("invalid_skill_author", "createdBy is required");
const models = boundedList(input.compatibility?.models, "compatibility.models");
if (models.length === 0 || models.length > MAX_SKILL_MODELS) {
throw new SkillLifecycleError("invalid_skill_compatibility", `compatibility.models must list 1-${MAX_SKILL_MODELS} models`);
}
const harness = input.compatibility?.harness?.trim();
if (!harness) throw new SkillLifecycleError("invalid_skill_compatibility", "compatibility.harness is required");
const contentSha256 = skillContentSha256(content);
const id = skillIdFor(name, contentSha256);
const { metadata, skill } = this.paths("candidate", id);
if (existsSync14(metadata)) {
throw new SkillLifecycleError(
"skill_candidate_exists",
`identical candidate ${id} already exists; changed behavior requires changed content`
);
}
const record2 = {
schema: SKILL_CANDIDATE_SCHEMA,
id,
name,
description,
contentSha256,
version: input.version ?? 1,
sources,
compatibility: { harness, models },
createdBy,
createdAt: this.now(),
...input.supersedes ? { supersedes: input.supersedes } : {}
};
this.write(skill, content);
this.write(metadata, `${JSON.stringify(record2, null, 2)}
`);
this.appendHistory(id, { schema: "kxm.skill-history-event.v1", event: "candidate_created", by: createdBy, supersedes: input.supersedes, at: record2.createdAt });
return record2;
}
/** Record a protected evaluation. A failed functional or safety evaluation
* deterministically quarantines the candidate. */
evaluate(candidateId, input) {
if (input.kind === "optimization" && !this.allowOptimizationEvals) {
throw new SkillLifecycleError(
"skill_optimization_disabled",
"optimization evaluations are disabled; enable them explicitly behind protected evals"
);
}
const metadata = this.readMetadata("candidate", candidateId);
const evaluatorVersion = input.evaluatorVersion?.trim();
if (!evaluatorVersion) throw new SkillLifecycleError("invalid_skill_evaluation", "evaluatorVersion is required");
const evaluation = {
schema: SKILL_EVALUATION_SCHEMA,
candidateId,
kind: input.kind,
evaluatorVersion,
passed: input.passed === true,
...input.score !== void 0 ? { score: input.score } : {},
...input.details ? { details: redactSecrets(input.details.slice(0, 2e3)) } : {},
evaluatedAt: this.now()
};
this.appendHistory(candidateId, evaluation);
let quarantined = false;
if (!evaluation.passed && (input.kind === "functional" || input.kind === "safety")) {
const decision = {
schema: SKILL_DECISION_SCHEMA,
candidateId,
decision: "quarantined",
decidedBy: input.evaluatedBy?.trim() || `evaluator:${evaluatorVersion}`,
reason: `automatic quarantine: ${input.kind} evaluation failed (${evaluatorVersion})`,
evidenceRefs: [`evaluation:${input.kind}:${evaluatorVersion}`],
decidedAt: this.now()
};
this.move("candidate", "quarantined", candidateId);
this.appendHistory(candidateId, decision);
quarantined = true;
}
return { evaluation, quarantined };
}
evaluationsFor(candidateId) {
return this.history(candidateId).filter(
(record2) => record2.schema === SKILL_EVALUATION_SCHEMA
);
}
/** Promote a candidate that passed every protected evaluation. The
* promoter must differ from the author, cite durable evidence, and the
* promoted content is hash-pinned and immutable. Emits a unified diff patch
* instead of moving the candidate directory. */
promote(candidateId, decision) {
const metadata = this.readMetadata("candidate", candidateId);
const decidedBy = decision.decidedBy?.trim();
if (!decidedBy) throw new SkillLifecycleError("invalid_skill_decision", "decidedBy is required");
if (decidedBy === metadata.createdBy) {
throw new SkillLifecycleError("skill_promotion_invalid", "the author of a skill candidate cannot promote it");
}
const evidenceRefs = boundedList(decision.evidenceRefs, "evidenceRefs");
if (evidenceRefs.length === 0) {
throw new SkillLifecycleError("skill_promotion_invalid", "promotion requires durable evidence references");
}
const evaluations = this.evaluationsFor(candidateId);
const missing = [];
for (const kind of PROMOTION_REQUIRED_EVALUATIONS) {
const latest = [...evaluations].reverse().find((record3) => record3.kind === kind);
if (!latest || !latest.passed) missing.push(kind);
}
if (missing.length > 0) {
throw new SkillLifecycleError(
"skill_evaluations_incomplete",
`promotion requires passing ${missing.join(", ")} evaluations`
);
}
this.verify("candidate", candidateId);
const record2 = {
schema: SKILL_DECISION_SCHEMA,
candidateId,
decision: "promoted",
decidedBy,
reason: decision.reason?.trim() || "passed protected evaluation",
evidenceRefs,
decidedAt: this.now()
};
const candidatePaths = this.paths("candidate", candidateId);
const promotedPaths = this.paths("promoted", candidateId);
const skillContent = readFileSync12(candidatePaths.skill, "utf8");
const metadataContent = readFileSync12(candidatePaths.metadata, "utf8");
this.write(promotedPaths.skill, skillContent);
this.write(promotedPaths.metadata, metadataContent);
const patchPath = join15(this.root, "patches", `${candidateId}.patch`);
const relSkillPath = `.kxm/skills/promoted/${candidateId}/SKILL.md`;
const relMetaPath = `.kxm/skills/promoted/${candidateId}/metadata.json`;
const patch = `${createUnifiedPatch(relSkillPath, skillContent)}${createUnifiedPatch(relMetaPath, metadataContent)}`;
this.write(patchPath, patch);
this.appendHistory(candidateId, record2);
return { ...metadata, patch, patchPath };
}
reject(candidateId, decision) {
const metadata = this.readMetadata("candidate", candidateId);
const record2 = {
schema: SKILL_DECISION_SCHEMA,
candidateId,
decision: "rejected",
decidedBy: decision.decidedBy?.trim() || "kxm-admin",
reason: decision.reason?.trim() || "rejected",
evidenceRefs: [],
decidedAt: this.now()
};
this.move("candidate", "rejected", candidateId);
this.appendHistory(candidateId, record2);
return metadata;
}
/** Verify content integrity of a stored skill (any state). Detects
* out-of-band edits to promoted skills and verifies standard YAML frontmatter. */
verify(state, id) {
const metadata = this.readMetadata(state, id);
const { skill } = this.paths(state, id);
const content = readFileSync12(skill, "utf8");
if (skillContentSha256(content) !== metadata.contentSha256) {
throw new SkillLifecycleError(
"skill_integrity_violation",
`skill ${id} content does not match its pinned hash; promoted skills are immutable and require a new candidate/eval cycle`
);
}
const { frontmatter } = parseSkillFrontmatter(content);
if (!frontmatter || typeof frontmatter.name !== "string" || !frontmatter.name.trim() || typeof frontmatter.description !== "string" || !frontmatter.description.trim()) {
throw new SkillLifecycleError(
"invalid_skill_frontmatter",
`skill ${id} must contain valid YAML frontmatter with 'name' and 'description'`
);
}
return metadata;
}
list(state) {
const dir = this.dir(state);
if (!existsSync14(dir)) return [];
const ids = readdirSorted(dir);
return ids.map((id) => {
try {
return this.readMetadata(state, id);
} catch {
return void 0;
}
}).filter((metadata) => metadata !== void 0);
}
read(state, id) {
const metadata = this.readMetadata(state, id);
const { skill } = this.paths(state, id);
return { metadata, content: readFileSync12(skill, "utf8") };
}
};
function boundedList(value, field) {
if (value === void 0) return [];
if (!Array.isArray(value)) {
throw new SkillLifecycleError("invalid_skill_input", `${field} must be an array of strings`);
}
const refs = value.map((ref) => String(ref).trim()).filter((ref) => ref.length > 0);
if (refs.length > MAX_SKILL_EVIDENCE_REFS) {
throw new SkillLifecycleError("invalid_skill_input", `${field} exceeds ${MAX_SKILL_EVIDENCE_REFS} references`);
}
return [...new Set(refs)];
}
function readdirSorted(dir) {
return readdirSync9(dir).filter((entry) => statSync3(join15(dir, entry)).isDirectory()).sort();
}
// plugins/kxm/src/dispatch-context.ts
var DISPATCH_CONTEXT_BUDGET_TOKENS = 4e3;
var DISPATCH_CONTEXT_MAX_PROJECT_ITEMS = 5;
var GAP_NOT_LOADED = "dispatch_context_not_loaded";
var GAP_FAILED = "dispatch_context_failed";
var GAP_GIT_UNAVAILABLE = "dispatch_context_withheld:git_unavailable";
var GAP_UNCOMMITTED = "dispatch_context_withheld:uncommitted";
var GAP_DRIFT = "dispatch_context_withheld:memory_revision_drift";
var GAP_MEMORY_UNREADABLE = "dispatch_context_memory_unreadable";
var GAP_SKILLS_UNREADABLE = "dispatch_context_skills_unreadable";
var DISPATCH_CONTEXT_PATHSPEC = [
":(glob).kxm/memory/*.md",
":(glob).kxm/skills/promoted/*/SKILL.md",
":(glob).kxm/skills/promoted/*/metadata.json"
];
var GIT_STATUS_TIMEOUT_MS = 5e3;
var EMPTY_DISPATCH_SOURCES = Object.freeze({
present: false,
pool: Object.freeze([]),
promoted: Object.freeze([]),
gaps: Object.freeze([]),
skippedUnboundScopes: 0
});
var NOT_LOADED_DISPATCH_SOURCES = Object.freeze({
present: true,
pool: Object.freeze([]),
promoted: Object.freeze([]),
gaps: Object.freeze([GAP_NOT_LOADED]),
skippedUnboundScopes: 0
});
function contextRoleForAgent(agentId) {
if (CONTEXT_ROLES.includes(agentId)) return agentId;
for (const role of CONTEXT_ROLES) {
if (agentId.startsWith(`${role}-`)) return role;
}
return agentId;
}
function dispatchContextPresent(projectRoot) {
return hasTopLevelMarkdown(join16(projectRoot, ".kxm", "memory")) || hasAnyEntry(join16(projectRoot, ".kxm", "skills", "promoted"));
}
function hasTopLevelMarkdown(dir) {
try {
return readdirSync10(dir, { withFileTypes: true }).some((entry) => entry.isFile() && extname3(entry.name) === ".md");
} catch {
return false;
}
}
function hasAnyEntry(dir) {
try {
return readdirSync10(dir).length > 0;
} catch {
return false;
}
}
function gitEnvironment2() {
return Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.toUpperCase().startsWith("GIT_")));
}
function committedGateGap(projectRoot) {
const result = spawnSync5("git", [
"--no-optional-locks",
"-C",
projectRoot,
"status",
"--porcelain=v1",
"--untracked-files=all",
"--ignored=matching",
"--",
...DISPATCH_CONTEXT_PATHSPEC
], {
encoding: "utf8",
env: gitEnvironment2(),
timeout: GIT_STATUS_TIMEOUT_MS,
windowsHide: true
});
if (result.error || result.status !== 0) return GAP_GIT_UNAVAILABLE;
if (typeof result.stdout !== "string" || result.stdout.length > 0) return GAP_UNCOMMITTED;
return void 0;
}
function gapId(value) {
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value) ? value : "invalid";
}
function withheld(gaps) {
return { present: true, pool: [], promoted: [], gaps: [...gaps], skippedUnboundScopes: 0 };
}
function loadDispatchContextSources(input) {
try {
const { projectRoot, projectId, pinnedMemoryRevision } = input;
if (!dispatchContextPresent(projectRoot)) return EMPTY_DISPATCH_SOURCES;
const gateGap = committedGateGap(projectRoot);
if (gateGap !== void 0) return withheld([gateGap]);
if (computeKxmMemoryRevision({ projectRoot }) !== pinnedMemoryRevision) return withheld([GAP_DRIFT]);
const gaps = [];
let records;
try {
records = loadAuthoredMemory(projectRoot);
} catch {
gaps.push(GAP_MEMORY_UNREADABLE);
records = [];
}
const pool = [];
let skippedUnboundScopes = 0;
for (const record2 of records) {
if (record2.scope !== "project" && record2.scope !== "operator") {
skippedUnboundScopes += 1;
continue;
}
try {
pool.push(memoryRecordToContextItem(record2, projectId));
} catch {
gaps.push(`dispatch_context_memory_rejected:${gapId(record2.id)}`);
}
}
const promoted = [];
try {
const lifecycle = new SkillLifecycle(join16(projectRoot, ".kxm", "skills"));
for (const metadata of lifecycle.list("promoted")) {
try {
promoted.push(lifecycle.verify("promoted", metadata.id));
} catch {
gaps.push(`dispatch_context_skill_unverified:${gapId(metadata.id)}`);
}
}
} catch {
gaps.push(GAP_SKILLS_UNREADABLE);
}
if (computeKxmMemoryRevision({ projectRoot }) !== pinnedMemoryRevision) return withheld([...gaps, GAP_DRIFT]);
return { present: true, pool, promoted, gaps, skippedUnboundScopes };
} catch {
return withheld([GAP_FAILED]);
}
}
function assembleDispatchContext(sources, input) {
const role = contextRoleForAgent(input.agentId);
try {
if (sources.pool.length === 0 && sources.promoted.length === 0) {
return { items: [], deliveredIds: [], renderDeferred: 0, role, unresolvedGaps: [...sources.gaps] };
}
const task = (input.task.trim() || input.stepId).slice(0, MAX_CONTEXT_TASK_CHARS);
const promoted = sources.promoted;
const snapshot = {
list: (state) => state === "promoted" ? [...promoted] : [],
verify: (state, id) => {
const found = state === "promoted" ? promoted.find((metadata) => metadata.id === id) : void 0;
if (!found) throw new Error("skill is not in the verified dispatch snapshot");
return found;
}
};
const { packet, audit } = arbitrate(
{
project: input.projectId,
role,
task,
workflowRunId: input.runId,
stageId: input.stepId,
budgetTokens: Math.min(rolePolicy(role).budgetTokens, DISPATCH_CONTEXT_BUDGET_TOKENS)
},
[...sources.pool],
promoted.length > 0 ? { skillLifecycle: snapshot } : {}
);
const byId = /* @__PURE__ */ new Map();
for (const section of [packet.currentState, packet.knowledge, packet.evidence, packet.episodes, packet.skills, packet.contradictions]) {
for (const item of section) byId.set(item.id, item);
}
const items = [];
let projectItems = 0;
let renderDeferred = 0;
for (const id of audit.selectedIds) {
const item = byId.get(id);
if (!item) continue;
const projectRouted = item.project !== "_shared" && item.kind !== "state" && item.kind !== "episode" && item.kind !== "skill";
if (projectRouted) {
if (projectItems >= DISPATCH_CONTEXT_MAX_PROJECT_ITEMS) {
renderDeferred += 1;
continue;
}
projectItems += 1;
}
items.push(item);
}
return {
items,
deliveredIds: items.map((item) => item.id),
renderDeferred,
role,
unresolvedGaps: [
...sources.gaps,
...packet.unresolvedGaps,
...renderDeferred > 0 ? [`dispatch_context_render_deferred:${renderDeferred}`] : []
],
audit
};
} catch {
return { items: [], deliveredIds: [], renderDeferred: 0, role, unresolvedGaps: [...sources.gaps, GAP_FAILED] };
}
}
// plugins/kxm/src/engine-artifacts.ts
import { join as join17 } from "node:path";
// plugins/kxm/src/artifacts-exist.ts
import { lstatSync as lstatSync5, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
import { isAbsolute as isAbsolute5, relative as relative4, resolve as resolve9 } from "node:path";
function staysUnder(root, candidate) {
const child = relative4(root, candidate);
return child === "" || !isAbsolute5(child) && child !== ".." && !child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`);
}
function verifyArtifactExists(rootInput, pathInput) {
const lexicalRoot = resolve9(rootInput);
const lexicalPath = resolve9(pathInput);
if (!staysUnder(lexicalRoot, lexicalPath)) {
return { ok: false, error: "artifact_outside_workspace_assets", path: lexicalPath };
}
let realRoot;
let realPath;
try {
realRoot = realpathSync4(lexicalRoot);
} catch {
return { ok: false, error: "artifact_unreadable", path: lexicalPath };
}
try {
realPath = realpathSync4(lexicalPath);
} catch {
return { ok: false, error: "artifact_missing", path: lexicalPath };
}
if (!staysUnder(realRoot, realPath)) {
return { ok: false, error: "artifact_outside_workspace_assets", path: lexicalPath };
}
try {
const link = lstatSync5(lexicalPath);
if (link.isSymbolicLink()) {
return { ok: false, error: "artifact_outside_workspace_assets", path: lexicalPath };
}
const artifact = statSync4(realPath);
if (!artifact.isFile()) return { ok: false, error: "artifact_not_file", path: lexicalPath };
if (artifact.size < 1) return { ok: false, error: "artifact_empty", path: lexicalPath };
return { ok: true, path: realPath, bytes: artifact.size };
} catch {
return { ok: false, error: "artifact_unreadable", path: lexicalPath };
}
}
// plugins/kxm/src/engine-artifacts.ts
var kxmArtifactsGateSeams = {};
function evaluateArtifactsGate(context, definition) {
const root = join17(context.projectRoot, ".kxm", "assets");
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
const startTime = process.hrtime.bigint();
let checkedCount = 0;
let failedCount = 0;
for (const [index, path] of definition.paths.entries()) {
checkedCount += 1;
const result = verifyArtifactExists(root, join17(root, path));
if (!result.ok) failedCount += 1;
kxmArtifactsGateSeams.afterPathChecked?.({ path, index, checkedCount, failedCount });
}
const elapsedNs = process.hrtime.bigint() - startTime;
const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
return {
completeness: "complete",
spawned: 0,
pid: null,
exitCode: null,
signal: null,
exitObserved: 0,
closeObserved: 0,
stopCause: "none",
signalsAttempted: "none",
errorClass: null,
stdoutSha256: null,
stdoutBytes: null,
stdoutComplete: null,
stderrSha256: null,
stderrBytes: null,
stderrComplete: null,
checkedCount,
failedCount,
elapsedMs: Math.max(0, Math.floor(Number(elapsedNs) / 1e6)),
startedAt,
finishedAt
};
}
// plugins/kxm/src/engine-command.ts
import { spawn as spawn2 } from "node:child_process";
import { createHash as createHash13 } from "node:crypto";
// plugins/kxm/src/safety-integrity.ts
var DESTRUCTIVE_COMMAND_PATTERNS = Object.freeze([
/^\s*rm\s+.*-[a-zA-Z]*r[a-zA-Z]*f/i,
/^\s*rm\s+.*-[a-zA-Z]*f[a-zA-Z]*r/i,
/^\s*rm\s+.*(-[a-zA-Z]*r[a-zA-Z]*\s+.*-[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*\s+.*-[a-zA-Z]*r[a-zA-Z]*)/i,
/^\s*git\s+reset\s+--hard/i,
/^\s*git\s+clean\s+-[a-zA-Z]*f/i,
/^\s*git\s+checkout\s+--\s+/i,
/^\s*git\s+restore\s+(\.|\*|--staged\s+(\.|\*))/i
]);
function assertCommandSeatbelt(command) {
for (const pattern of DESTRUCTIVE_COMMAND_PATTERNS) {
if (pattern.test(command)) {
throw new Error(
`Command blocked by KXM safety seatbelt: "${command}". Destructive workspace mutations require explicit operator override.`
);
}
}
}
var INSECURE_SSH_HOST_KEY_PATTERNS = Object.freeze([
/StrictHostKeyChecking=(accept-new|no|off)/i,
/UserKnownHostsFile=\/dev\/null/i
]);
function assertPinnedSshHostKeyPolicy(sshArgs) {
for (const arg of sshArgs) {
for (const pattern of INSECURE_SSH_HOST_KEY_PATTERNS) {
if (pattern.test(arg)) {
throw new Error(
`Insecure SSH host key policy rejected: "${arg}". KXM headless SSH requires pinned host keys with StrictHostKeyChecking=yes and BatchMode=yes.`
);
}
}
}
}
// plugins/kxm/src/engine-command.ts
var MAX_DIRECT_TIMER_MS = 2147483647;
var COMMAND_TERM_GRACE_MS = 2e3;
var COMMAND_FINAL_WAIT_MS = 2e3;
var COMMAND_LINGER_MS = 2e3;
var kxmCommandGateSeams = {};
var POST_SPAWN_CHILD_ERROR_CLASS = "stream-error";
function createCommandObserver(input) {
return new CommandObserver(input);
}
var StreamDigest = class {
hash = createHash13("sha256");
bytes = 0;
complete = 0;
digest() {
return `sha256:${this.hash.copy().digest("hex")}`;
}
write(chunk) {
this.hash.update(chunk);
this.bytes += chunk.length;
}
end() {
this.complete = 1;
}
};
var CommandObserver = class {
definition;
cwd;
signal;
onSpawned;
termGraceMs;
finalWaitMs;
lingerMs;
child;
observedPid;
canSignal = true;
handedOff = false;
cleanupStarted = false;
spawnSeen = 0;
exitObserved = 0;
closeObserved = 0;
exitCode = null;
signalName = null;
stopCause = "none";
signalsAttempted = "none";
errorClass = null;
startedAt;
finishedAt = null;
startedMono = process.hrtime.bigint();
stdout = new StreamDigest();
stderr = new StreamDigest();
timeoutTimer;
termTimer;
finalTimer;
lingerTimer;
resolveOutcome;
abortListener;
constructor(input) {
this.definition = input.definition;
this.cwd = input.cwd;
this.signal = input.signal;
this.onSpawned = input.onSpawned;
const timing = kxmCommandGateSeams.timing;
this.termGraceMs = clampTimer(timing?.termGraceMs ?? COMMAND_TERM_GRACE_MS);
this.finalWaitMs = clampTimer(timing?.finalWaitMs ?? COMMAND_FINAL_WAIT_MS);
this.lingerMs = clampTimer(timing?.lingerMs ?? COMMAND_LINGER_MS);
this.startedAt = (/* @__PURE__ */ new Date()).toISOString();
this.abortListener = () => this.requestStop("cancel");
}
requestStop(cause, errorClass) {
if (cause === "none") return;
if (this.stopCause === "none") {
this.stopCause = cause;
if (errorClass && this.errorClass === null) this.errorClass = errorClass;
kxmCommandGateSeams.afterStopRequested?.(cause);
this.clearTimer("linger");
this.beginSignalSequence();
return;
}
if (errorClass && this.errorClass === null) this.errorClass = errorClass;
}
beginBoundedCleanup() {
this.cleanupStarted = true;
this.requestStop("error", "lost-close");
}
run() {
return new Promise((resolve15) => {
this.resolveOutcome = resolve15;
try {
this.start();
} catch (error) {
if (this.child !== void 0 || this.spawnSeen === 1 || this.observedPid !== void 0) {
this.requestStop("error", "stop-error");
return;
}
this.finishNoStart("validation", error);
}
});
}
start() {
if (this.signal.aborted || this.cleanupStarted) {
this.finishNoStart(this.signal.aborted ? "cancel" : "lost-close");
return;
}
try {
kxmCommandGateSeams.beforeSpawn?.(this.definition);
} catch {
this.finishNoStart("validation");
return;
}
if (this.signal.aborted || this.cleanupStarted) {
this.finishNoStart(this.signal.aborted ? "cancel" : "lost-close");
return;
}
if (!Number.isInteger(this.definition.timeoutMs) || this.definition.timeoutMs < 1 || this.definition.timeoutMs > MAX_DIRECT_TIMER_MS) {
throw runtimeError("run_events_illegal", "command", "command timeoutMs exceeds the direct timer bound");
}
assertCommandSeatbelt(this.definition.argv.join(" "));
this.startedAt = (/* @__PURE__ */ new Date()).toISOString();
let child;
try {
child = spawn2(this.definition.argv[0], this.definition.argv.slice(1), {
cwd: this.cwd,
env: process.env,
shell: false,
detached: true,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true
});
} catch {
this.finishNoStart("validation");
return;
}
this.child = child;
this.observePid(child.pid);
this.armTimeout();
this.signal.addEventListener("abort", this.abortListener);
this.attachChild(child);
}
attachChild(child) {
child.stdout?.on("data", (chunk) => {
if (this.handedOff) return;
try {
this.stdout.write(chunk);
} catch {
this.requestStop("error", "stream-error");
}
});
child.stderr?.on("data", (chunk) => {
if (this.handedOff) return;
try {
this.stderr.write(chunk);
} catch {
this.requestStop("error", "stream-error");
}
});
child.stdout?.on("end", () => {
if (this.handedOff) return;
try {
this.stdout.end();
} catch {
this.requestStop("error", "stream-error");
}
});
child.stderr?.on("end", () => {
if (this.handedOff) return;
try {
this.stderr.end();
} catch {
this.requestStop("error", "stream-error");
}
});
child.stdout?.on("error", () => this.requestStop("error", "stream-error"));
child.stderr?.on("error", () => this.requestStop("error", "stream-error"));
child.once("spawn", () => {
this.spawnSeen = 1;
this.observePid(child.pid);
if (this.observedPid !== void 0) {
this.notifySpawned();
} else {
this.requestStop("error", POST_SPAWN_CHILD_ERROR_CLASS);
}
});
child.once("error", () => {
if (this.spawnSeen === 0 && child.pid == null && this.observedPid === void 0) {
this.finishNoStart("spawn-error");
return;
}
if (this.spawnSeen === 0) {
this.spawnSeen = 1;
this.observePid(child.pid);
this.notifySpawned();
}
this.requestStop("error", POST_SPAWN_CHILD_ERROR_CLASS);
});
child.once("exit", (code, signal) => {
this.exitObserved = 1;
this.exitCode = code;
this.signalName = signal;
if (this.closeObserved === 1) {
this.handoff();
return;
}
this.armLinger();
});
child.once("close", () => {
this.closeObserved = 1;
this.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
this.canSignal = false;
this.clearTimer("term");
this.clearTimer("final");
this.clearTimer("linger");
this.clearTimer("timeout");
child.stdout?.destroy();
child.stderr?.destroy();
dropKxmCommandStopCapability(this);
try {
kxmCommandGateSeams.afterChildClose?.();
} catch {
}
this.handoff();
});
}
notifiedSpawned = false;
observePid(pid) {
if (this.observedPid === void 0 && typeof pid === "number" && pid > 0) {
this.observedPid = pid;
}
}
notifySpawned() {
if (this.notifiedSpawned || this.observedPid === void 0) return;
this.notifiedSpawned = true;
try {
this.onSpawned(this.observedPid);
} catch {
this.requestStop("error", "recording-error");
}
try {
kxmCommandGateSeams.afterSpawned?.(this.observedPid);
} catch {
this.requestStop("error", "recording-error");
}
}
armTimeout() {
this.timeoutTimer = schedule(this.definition.timeoutMs, () => {
this.requestStop("timeout");
});
}
armLinger() {
if (this.stopCause !== "none") return;
if (this.lingerTimer || this.closeObserved === 1) return;
this.lingerTimer = schedule(this.lingerMs, () => {
this.requestStop("error", "lost-close");
});
}
beginSignalSequence() {
if (this.closeObserved === 1 || this.handedOff) {
this.handoff();
return;
}
const pid = this.observedPid;
if (!this.canSignal || pid === void 0) {
this.armFinal();
return;
}
this.signalGroup(pid, "SIGTERM", "term");
this.termTimer = schedule(this.termGraceMs, () => {
if (this.closeObserved === 1 || this.handedOff) return;
if (!this.canSignal || this.observedPid === void 0) {
this.armFinal();
return;
}
this.signalGroup(this.observedPid, "SIGKILL", "term-kill");
this.armFinal();
});
}
signalGroup(pid, signal, attempted) {
if (!this.canSignal || this.closeObserved === 1 || pid <= 0) return;
try {
process.kill(-pid, signal);
this.signalsAttempted = attempted;
} catch (error) {
const code = error.code;
if (code === "ESRCH") {
this.canSignal = false;
return;
}
if (this.errorClass === null) this.errorClass = "stop-error";
}
}
armFinal() {
if (this.finalTimer) return;
this.finalTimer = schedule(this.finalWaitMs, () => {
this.canSignal = false;
this.handoff();
});
}
finishNoStart(kind, _error) {
if (this.handedOff) return;
if (kind === "lost-close" && this.spawnSeen === 1) {
this.requestStop("error", "lost-close");
return;
}
const now = (/* @__PURE__ */ new Date()).toISOString();
const cancel = kind === "cancel";
this.handoffWith({
kind: "no-start",
observation: this.baseObservation({
completeness: "no-start",
spawned: 0,
pid: null,
exitCode: null,
signal: null,
exitObserved: 0,
closeObserved: 0,
stopCause: cancel ? "cancel" : "none",
signalsAttempted: "none",
errorClass: cancel ? null : kind === "spawn-error" ? "spawn-error" : "validation",
stdoutSha256: null,
stdoutBytes: null,
stdoutComplete: null,
stderrSha256: null,
stderrBytes: null,
stderrComplete: null,
finishedAt: now
})
});
}
handoff() {
if (this.handedOff) return;
if (this.spawnSeen === 0 && this.observedPid === void 0) {
if (this.stopCause === "cancel" || this.signal.aborted) {
this.finishNoStart("cancel");
return;
}
if (this.errorClass === "spawn-error") {
this.finishNoStart("spawn-error");
return;
}
this.finishNoStart("validation");
return;
}
const observation = this.snapshot();
if (isCompleteNormal(observation)) {
this.handoffWith({ kind: "complete", observation });
return;
}
this.handoffWith({
kind: "uncertain",
reason: this.uncertaintyReason(observation),
observation: { ...observation, completeness: "incomplete" }
});
}
uncertaintyReason(observation) {
if (this.stopCause === "timeout") return "timeout";
if (this.stopCause === "cancel") return "cancel";
if (this.errorClass === "recording-error") return "recording-error";
if (this.errorClass === "lost-close" || this.exitObserved === 1 && this.closeObserved === 0) return "lost-close";
if (this.errorClass === "stop-error") return "stop-error";
if (this.errorClass === "stream-error") return "stream-error";
if (this.stopCause === "error") return "stream-error";
if (observation.signal !== null) return "signal-termination";
return "stop-error";
}
snapshot() {
return this.baseObservation({
completeness: "complete",
spawned: this.spawnSeen,
pid: this.observedPid ?? null,
exitCode: this.signalName !== null ? null : this.exitCode,
signal: this.signalName,
exitObserved: this.exitObserved,
closeObserved: this.closeObserved,
stopCause: this.stopCause,
signalsAttempted: this.signalsAttempted,
errorClass: this.errorClass,
stdoutSha256: this.stdout.digest(),
stdoutBytes: this.stdout.bytes,
stdoutComplete: this.stdout.complete,
stderrSha256: this.stderr.digest(),
stderrBytes: this.stderr.bytes,
stderrComplete: this.stderr.complete,
finishedAt: this.finishedAt
});
}
baseObservation(facts) {
const elapsedNs = process.hrtime.bigint() - this.startedMono;
return {
...facts,
checkedCount: null,
failedCount: null,
elapsedMs: facts.elapsedMs ?? Math.max(0, Math.floor(Number(elapsedNs) / 1e6)),
startedAt: facts.startedAt ?? this.startedAt
};
}
handoffWith(outcome) {
if (this.handedOff) return;
this.handedOff = true;
this.canSignal = false;
this.signal.removeEventListener("abort", this.abortListener);
this.clearTimer("timeout");
this.clearTimer("term");
this.clearTimer("final");
this.clearTimer("linger");
this.child?.unref();
dropKxmCommandStopCapability(this);
this.resolveOutcome?.(outcome);
}
clearTimer(name) {
const current = this[`${name}Timer`];
if (current) clearTimeout(current);
this[`${name}Timer`] = void 0;
}
};
function dropKxmCommandStopCapability(observer) {
observer.requestStop = () => void 0;
}
function isCompleteNormal(observation) {
return observation.completeness === "complete" && observation.spawned === 1 && typeof observation.pid === "number" && typeof observation.exitCode === "number" && observation.signal === null && observation.exitObserved === 1 && observation.closeObserved === 1 && observation.stopCause === "none" && observation.signalsAttempted === "none" && observation.errorClass === null && observation.stdoutComplete === 1 && observation.stderrComplete === 1 && typeof observation.stdoutSha256 === "string" && typeof observation.stderrSha256 === "string";
}
function clampTimer(ms) {
if (!Number.isInteger(ms) || ms < 0 || ms > MAX_DIRECT_TIMER_MS) {
throw runtimeError("run_events_illegal", "command", "command timer is outside the direct timer bound");
}
return ms;
}
function schedule(ms, fn) {
return setTimeout(fn, clampTimer(ms));
}
// plugins/kxm/src/engine-gate-records.ts
function recordGateIntentInTransaction(context, run, envelope2, stepId) {
const step = requireGateStep(envelope2, stepId, run.runId);
const definition = envelope2.gates.definitions[step.gate];
if (!definition || definition.kind === "reserved") {
throw runtimeError("gate_row_invalid", run.runId, "reserved gates cannot record intent in this slice");
}
const folded = foldStoredKxmRun(context, run);
const used = folded.stepAttempts[stepId] ?? 0;
const stepAttempt = used + 1;
const assignmentId = newKxmAssignmentId();
const attemptId = newKxmAttemptId();
const effectId = newKxmEffectId();
const minted = mintKxmCapabilitySecret();
const now = (/* @__PURE__ */ new Date()).toISOString();
const seq = sequencer(context, run, now);
seq.push("step.entered", { stepId, stepAttempt, status: "pending" });
seq.push("step.status_changed", { stepId, status: "preparing", previousStatus: "pending" });
seq.push("assignment.created", { assignmentId, stepId, stepAttempt, agentId: "coordinator", status: "created" });
seq.push("assignment.accepted", { assignmentId, stepId, stepAttempt, attemptId, status: "accepted" });
seq.push("attempt.created", { attemptId, assignmentId, stepId, stepAttempt, status: "created" });
seq.push("assignment.dispatched", { assignmentId, stepId, stepAttempt, attemptId, capabilityHash: minted.hash, status: "dispatched" });
seq.push("attempt.status_changed", { attemptId, assignmentId, stepId, stepAttempt, status: "starting" });
seq.push("step.status_changed", { stepId, status: "running", previousStatus: "preparing" });
const policyClass = definition.kind === "artifacts-exist" ? "read-only" : "unknown";
const intent = seq.push("effect.intent_recorded", {
effect: { id: effectId, policy: { class: policyClass, sharedMutable: false } },
stepId,
stepAttempt,
assignmentId,
attemptId
});
for (const event of seq.events) context.eventStore.appendEvent(event);
context.eventStore.insertCapability({
attemptId,
runId: run.runId,
assignmentId,
stepId,
stepAttempt,
producerId: "kxm-gate",
capabilityHash: minted.hash,
state: "issued"
});
const attemptRow = {
attemptId,
runId: run.runId,
projectId: run.projectId,
homeRuntimeId: run.homeRuntimeId,
stepId,
stepAttempt,
assignmentId,
effectId,
gateId: step.gate,
gateKind: definition.kind,
expect: step.expect,
gateDefinitionHash: gateDefinitionHash(step.gate, definition),
registryHash: envelope2.gates.registry.hash,
runPlanHash: envelope2 && folded.runPlanHash ? folded.runPlanHash : hashFromStore(context, run.runId),
controlProjectKey: envelope2.gates.controlRoot.projectKey,
producerId: "kxm-gate",
intentEventId: intent.eventId,
contentHash: ""
};
attemptRow.runPlanHash = context.eventStore.runPlan(run.runId).runPlanHash;
const withHash = { ...attemptRow, contentHash: gateRowContentHash("gate_attempts", { ...attemptRow, contentHash: "" }) };
context.eventStore.insertGateAttempt(withHash);
return persist(context, run, now, seq.events.at(-1).sequence);
}
function recordGateSpawnedInTransaction(context, run, envelope2, stepId) {
const ids = requireIntent(context, run, envelope2, stepId);
if (ids.gateKind !== "command") throw runtimeError("gate_row_invalid", run.runId, "effect.dispatched is command-only");
const now = (/* @__PURE__ */ new Date()).toISOString();
const seq = sequencer(context, run, now);
seq.push("assignment.executing", { assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, attemptId: ids.attemptId, status: "executing" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, status: "executing" });
seq.push("effect.dispatched", {
effect: { id: ids.effectId, policy: { class: "unknown", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId
});
for (const event of seq.events) context.eventStore.appendEvent(event);
return persist(context, run, now, seq.events.at(-1).sequence);
}
function recordGateSettlementInTransaction(context, run, envelope2, stepId, observation) {
const ids = requireIntent(context, run, envelope2, stepId);
assertClosedGateObservation(ids.gateKind, observation);
const outcome = computeGateEvidenceOutcome(ids.gateKind, ids.expect, observation);
const now = (/* @__PURE__ */ new Date()).toISOString();
const seq = sequencer(context, run, now);
if (ids.gateKind === "artifacts-exist") {
seq.push("assignment.executing", { assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, attemptId: ids.attemptId, status: "executing" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, status: "executing" });
seq.push("effect.dispatched", {
effect: { id: ids.effectId, policy: { class: "read-only", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId
});
}
seq.push("attempt.status_changed", { attemptId: ids.attemptId, assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, status: "settling" });
const observationId = newKxmObservationId();
const observed = seq.push("effect.observed", {
effect: { id: ids.effectId, policy: { class: ids.gateKind === "artifacts-exist" ? "read-only" : "unknown", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
receipt: placeholderReceipt(observationId, ids.gateKind, now)
});
const observationRow = buildObservation(ids, observation, observationId, observed.eventId);
patchReceipt(observed, observationRow);
const evidenceId = newKxmEvidenceId();
const evidenceDraft = {
evidenceId,
attemptId: ids.attemptId,
observationId,
runId: run.runId,
projectId: run.projectId,
homeRuntimeId: run.homeRuntimeId,
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
effectId: ids.effectId,
evidenceKey: evidenceKeyFor(envelope2, stepId),
kind: "gate",
expect: ids.expect,
outcome,
settledEventId: "evt_pending00000000000000000000000",
contentHash: ""
};
const settled = seq.push("effect.settled", {
effect: { id: ids.effectId, policy: { class: ids.gateKind === "artifacts-exist" ? "read-only" : "unknown", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
outcome,
evidenceRefs: [{ id: evidenceId, kind: "gate", hash: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", status: "settled" }]
});
evidenceDraft.settledEventId = settled.eventId;
evidenceDraft.contentHash = gateRowContentHash("gate_evidence", { ...evidenceDraft, contentHash: "" });
settled.payload.evidenceRefs[0].hash = evidenceDraft.contentHash;
appendEvaluatedTail(seq, envelope2, ids, stepId, outcome);
for (const event of seq.events) context.eventStore.appendEvent(event);
context.eventStore.insertGateObservation(observationRow);
context.eventStore.insertGateEvidence(evidenceDraft);
context.eventStore.settleCapability(ids.attemptId, "settled");
return persist(context, run, now, seq.events.at(-1).sequence);
}
function recordGateNoStartInTransaction(context, run, envelope2, stepId, observation) {
const ids = requireIntent(context, run, envelope2, stepId);
assertClosedGateObservation(ids.gateKind, observation);
if (observation.completeness !== "no-start") {
throw runtimeError("gate_row_invalid", run.runId, "no-start proof requires spawned 0 and completeness no-start");
}
const cancelled = observation.stopCause === "cancel";
const now = (/* @__PURE__ */ new Date()).toISOString();
const seq = sequencer(context, run, now);
const cancelReason = cancelled ? ensureOperatorCancel(seq, ids.state, run, context) : void 0;
const observationId = newKxmObservationId();
const observed = seq.push("effect.observed", {
effect: { id: ids.effectId, policy: { class: ids.gateKind === "artifacts-exist" ? "read-only" : "unknown", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
receipt: placeholderReceipt(observationId, ids.gateKind, now)
});
const observationRow = buildObservation(ids, observation, observationId, observed.eventId);
patchReceipt(observed, observationRow);
seq.push("attempt.status_changed", { attemptId: ids.attemptId, assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, status: "settling" });
seq.push("effect.settled", {
effect: { id: ids.effectId, policy: { class: ids.gateKind === "artifacts-exist" ? "read-only" : "unknown", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
receipt: {
provider: "kxm-gate",
kind: ids.gateKind,
id: observationId,
hash: observationRow.contentHash,
observedAt: now
}
});
if (cancelled) {
seq.push("assignment.result_recorded", { assignmentId: ids.assignmentId, resultClass: "cancelled", status: "result_recorded" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, status: "terminal" });
seq.push("assignment.terminal", { assignmentId: ids.assignmentId, outcome: "cancelled", status: "terminal" });
seq.push("step.status_changed", { stepId, status: "cancelled", previousStatus: "running" });
seq.push("run.status_changed", { status: "cancelled", reason: cancelReason ?? "operator_cancel", stepId });
} else {
seq.push("assignment.result_recorded", { assignmentId: ids.assignmentId, resultClass: "producer_rejected", status: "result_recorded" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, status: "terminal" });
seq.push("assignment.terminal", { assignmentId: ids.assignmentId, outcome: "failed", status: "terminal" });
seq.push("step.status_changed", { stepId, status: "failed", previousStatus: "running" });
seq.push("run.status_changed", { status: "failed", reason: "gate_start_failed", stepId });
}
for (const event of seq.events) context.eventStore.appendEvent(event);
context.eventStore.insertGateObservation(observationRow);
context.eventStore.settleCapability(ids.attemptId, "settled");
return persist(context, run, now, seq.events.at(-1).sequence);
}
function recordGateUncertainInTransaction(context, run, envelope2, stepId, reason, observation) {
const ids = requireIntent(context, run, envelope2, stepId);
if (observation.completeness !== "incomplete") {
throw runtimeError("gate_row_invalid", run.runId, "uncertainty observation must be incomplete");
}
const effectState = ids.state.currentStep?.effectState;
if (effectState === "observed-complete" || effectState === "observed-no-start" || effectState === "observed-unknown" || effectState === "settled" || effectState === "settled-proof") {
throw runtimeError("run_events_illegal", run.runId, "blocked_uncertain after an observation is illegal");
}
if (context.eventStore.gateObservationForAttempt(ids.attemptId)) {
throw runtimeError("run_events_illegal", run.runId, "a completed observation cannot be rewritten");
}
const now = (/* @__PURE__ */ new Date()).toISOString();
const seq = sequencer(context, run, now);
const observationId = newKxmObservationId();
const blocked = seq.push("effect.blocked_uncertain", {
effect: { id: ids.effectId, policy: { class: ids.gateKind === "artifacts-exist" ? "read-only" : "unknown", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
reason,
receipt: placeholderReceipt(observationId, ids.gateKind, now)
});
const observationRow = buildObservation(ids, observation, observationId, blocked.eventId);
patchReceipt(blocked, observationRow);
for (const event of seq.events) context.eventStore.appendEvent(event);
context.eventStore.insertGateObservation(observationRow);
return persist(context, run, now, seq.events.at(-1).sequence);
}
function recordGateCancelObservedInTransaction(context, run, envelope2, stepId, observation) {
const ids = requireIntent(context, run, envelope2, stepId);
assertClosedGateObservation(ids.gateKind, observation);
if (observation.completeness !== "complete") {
throw runtimeError("gate_row_invalid", run.runId, "cancel-after-observation requires a complete observation");
}
if (ids.gateKind === "command" && ids.state.currentStep?.effectState !== "dispatched") {
throw runtimeError("run_events_illegal", run.runId, "complete command observations require effect.dispatched");
}
const now = (/* @__PURE__ */ new Date()).toISOString();
const seq = sequencer(context, run, now);
const cancelReason = ensureOperatorCancel(seq, ids.state, run, context);
if (ids.gateKind === "artifacts-exist") {
seq.push("assignment.executing", { assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, attemptId: ids.attemptId, status: "executing" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, status: "executing" });
seq.push("effect.dispatched", {
effect: { id: ids.effectId, policy: { class: "read-only", sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId
});
}
seq.push("attempt.status_changed", { attemptId: ids.attemptId, assignmentId: ids.assignmentId, stepId, stepAttempt: ids.stepAttempt, status: "settling" });
const observationId = newKxmObservationId();
const policyClass = ids.gateKind === "artifacts-exist" ? "read-only" : "unknown";
const observed = seq.push("effect.observed", {
effect: { id: ids.effectId, policy: { class: policyClass, sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
receipt: placeholderReceipt(observationId, ids.gateKind, now)
});
const observationRow = buildObservation(ids, observation, observationId, observed.eventId);
patchReceipt(observed, observationRow);
seq.push("effect.settled", {
effect: { id: ids.effectId, policy: { class: policyClass, sharedMutable: false } },
stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
attemptId: ids.attemptId,
receipt: {
provider: "kxm-gate",
kind: ids.gateKind,
id: observationId,
hash: observationRow.contentHash,
observedAt: now
}
});
seq.push("assignment.result_recorded", { assignmentId: ids.assignmentId, resultClass: "cancelled", status: "result_recorded" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, status: "terminal" });
seq.push("assignment.terminal", { assignmentId: ids.assignmentId, outcome: "cancelled", status: "terminal" });
seq.push("step.status_changed", { stepId, status: "cancelled", previousStatus: "running" });
seq.push("run.status_changed", { status: "cancelled", reason: cancelReason, stepId });
for (const event of seq.events) context.eventStore.appendEvent(event);
context.eventStore.insertGateObservation(observationRow);
context.eventStore.settleCapability(ids.attemptId, "settled");
return persist(context, run, now, seq.events.at(-1).sequence);
}
function appendEvaluatedTail(seq, envelope2, ids, stepId, outcome) {
const mapped = outcome === "passed" ? "passed" : outcome === "repro-missing" ? "failed" : "failed";
seq.push("assignment.result_recorded", { assignmentId: ids.assignmentId, resultClass: "outcome", outcome, status: "result_recorded" });
seq.push("attempt.status_changed", { attemptId: ids.attemptId, status: "terminal" });
seq.push("assignment.terminal", { assignmentId: ids.assignmentId, outcome, status: "terminal" });
seq.push("step.outcome_recorded", { stepId, stepAttempt: ids.stepAttempt, outcome });
seq.push("step.status_changed", { stepId, status: mapped, previousStatus: "running" });
const selected = envelope2.plan.steps[stepId].transitions[outcome];
if (!selected) {
seq.push("run.status_changed", { status: "failed", reason: "outcome_unknown", stepId, outcome });
return;
}
const budget = kxmTransitionBudgetFailure(envelope2.plan, ids.state, stepId, outcome);
if (budget) {
seq.push("run.status_changed", { status: "failed", reason: budget, stepId, outcome });
return;
}
if (selected.to === "step") {
seq.push("step.transitioned", { fromStepId: stepId, toStepId: selected.target, outcome });
} else {
seq.push("step.transitioned", { fromStepId: stepId, status: selected.terminalStatus, outcome });
seq.push("run.status_changed", { status: selected.terminalStatus });
}
}
function evidenceKeyFor(envelope2, stepId) {
const required2 = envelope2.plan.steps[stepId]?.requiredEvidence.filter((item) => item.kind === "gate") ?? [];
return required2.length === 1 ? required2[0].key : null;
}
function placeholderReceipt(observationId, kind, now) {
return {
provider: "kxm-gate",
kind,
id: observationId,
hash: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
observedAt: now
};
}
function patchReceipt(event, row) {
const receipt = event.payload.receipt;
receipt.hash = row.contentHash;
}
function buildObservation(ids, observation, observationId, recordedEventId) {
const row = {
observationId,
attemptId: ids.attemptId,
runId: ids.runId,
projectId: ids.projectId,
homeRuntimeId: ids.homeRuntimeId,
stepId: ids.stepId,
stepAttempt: ids.stepAttempt,
assignmentId: ids.assignmentId,
effectId: ids.effectId,
...observation,
recordedEventId,
contentHash: ""
};
return { ...row, contentHash: gateRowContentHash("gate_observations", { ...row, contentHash: "" }) };
}
function requireGateStep(envelope2, stepId, runId) {
const step = envelope2.plan.steps[stepId];
if (!step || step.kind !== "gate") throw runtimeError("run_events_illegal", runId, `step ${stepId} is not a gate`);
return step;
}
function requireIntent(context, run, envelope2, stepId) {
const step = requireGateStep(envelope2, stepId, run.runId);
const folded = foldStoredKxmRun(context, run);
const attemptId = folded.currentStep?.attemptId;
if (!attemptId || folded.currentStep?.stepId !== stepId) {
throw runtimeError("run_events_illegal", run.runId, "gate intent has not been recorded");
}
const row = context.eventStore.gateAttempt(attemptId);
if (!row) throw runtimeError("gate_row_invalid", run.runId, "missing gate attempt");
return {
...row,
gateKind: row.gateKind,
expect: step.expect,
state: folded
};
}
function ensureOperatorCancel(seq, state, run, context) {
if (state.status === "cancelling") return cancelReasonFromLog(context, run.runId);
if (state.status !== "running") {
throw runtimeError("run_events_illegal", run.runId, "cancelled gate proof requires a running or cancelling run");
}
seq.push("run.cancel_requested", {
actor: { kind: "runtime", id: run.homeRuntimeId },
reason: "operator_cancel"
});
seq.push("run.status_changed", { status: "cancelling", reason: "operator_cancel" });
return "operator_cancel";
}
function cancelReasonFromLog(context, runId) {
const events = context.eventStore.events(runId, 0, 1e6);
for (let index = events.length - 1; index >= 0; index -= 1) {
const event = events[index];
if (event.eventType === "run.cancel_requested" && typeof event.payload.reason === "string") {
return event.payload.reason;
}
}
return "operator_cancel";
}
function sequencer(context, run, now) {
let sequence = context.eventStore.nextSequence(run.runId);
let mono = kxmMonotonicNs();
const events = [];
return {
events,
push(eventType, payload) {
const event = {
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
};
mono = kxmIncrementMonotonicNs(mono);
events.push(event);
return event;
}
};
}
function persist(context, run, now, lastSequence) {
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, lastSequence);
context.eventStore.updateRunStatus(run.runId, next.status, now);
return { state: next, run: { ...run, status: next.status, updatedAt: now } };
}
function hashFromStore(context, runId) {
return context.eventStore.runPlan(runId).runPlanHash;
}
// plugins/kxm/src/routing.ts
import { createHash as createHash14 } from "node:crypto";
var ROUTING_RECORD_V2_SCHEMA = "kxm.routing-record.v2";
var BEHAVIORAL_HASH_VERSION = 1;
var MAX_PROVIDER_METADATA_FIELDS = 32;
function normalizeModel(value) {
if (value === void 0) return void 0;
const normalized = value.trim().toLowerCase().replace(/\s+/g, "-");
return normalized === "" ? void 0 : normalized;
}
function behavioralConfigHash(input) {
const canonical = {
version: BEHAVIORAL_HASH_VERSION,
requestedModel: normalizeModel(input.requestedModel) ?? null,
effectiveModel: normalizeModel(input.effectiveModel) ?? null,
reasoningEffort: input.reasoningEffort?.trim() ?? null,
agentRole: input.agentRole ? input.agentRole.trim().toLowerCase().replace(/\s+/g, "-") : null,
rolePromptSha256: input.rolePromptSha256?.trim() ?? null,
skills: (input.skills ?? []).map((skill) => ({ id: skill.id.trim(), sha: skill.contentSha256.trim() })).sort((left, right) => left.id.localeCompare(right.id) || left.sha.localeCompare(right.sha)),
contextPolicyVersion: input.contextPolicyVersion?.trim() ?? null,
toolPolicyVersion: input.toolPolicyVersion?.trim() ?? null,
workflowDefinitionSha256: input.workflowDefinitionSha256?.trim() ?? null,
verifierConfigSha256: input.verifierConfigSha256?.trim() ?? null
};
return createHash14("sha256").update(JSON.stringify(canonical), "utf8").digest("hex");
}
function boundedInt(value, field) {
if (value === void 0 || value === null) return void 0;
if (!Number.isInteger(value) || value < 0 || value > 1e6) {
throw new Error(`${field} must be an integer between 0 and 1000000`);
}
return value;
}
function boundedString(value, field, max) {
if (value === void 0 || value === null) return void 0;
if (typeof value !== "string" || value.length > max) {
throw new Error(`${field} must be a string of at most ${max} characters`);
}
return value;
}
function parseRoutingRecordV2(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("routing record v2 must be an object");
}
const input = value;
if (input.schema !== ROUTING_RECORD_V2_SCHEMA) {
throw new Error(`routing record v2 schema must be ${ROUTING_RECORD_V2_SCHEMA}`);
}
const costBasis = input.costBasis;
if (costBasis !== "metered" && costBasis !== "unmetered" && costBasis !== "unknown") {
throw new Error("routing record v2 costBasis must be metered, unmetered, or unknown");
}
let costUsd = void 0;
if (costBasis === "metered") {
if (typeof input.costUsd !== "number" || !Number.isFinite(input.costUsd) || input.costUsd < 0 || input.costUsd > 1e6) {
throw new Error("routing record v2 costUsd must be a non-negative finite number when costBasis is metered");
}
costUsd = input.costUsd;
} else if (input.costUsd !== void 0 && input.costUsd !== null) {
if (typeof input.costUsd !== "number" || !Number.isFinite(input.costUsd) || input.costUsd < 0) {
throw new Error("routing record v2 costUsd must be a non-negative finite number when present");
}
costUsd = input.costUsd;
} else {
costUsd = null;
}
const rawHash = boundedString(input.behavioralSha256, "behavioralSha256", 72) ?? "";
if (!/^(?:sha256:)?[a-f0-9]{64}$/.test(rawHash)) {
throw new Error("routing record v2 behavioralSha256 must be a sha256 hex digest");
}
const behavioralSha256 = rawHash.startsWith("sha256:") ? rawHash : `sha256:${rawHash}`;
const latencyMs = input.latencyMs;
if (typeof latencyMs !== "number" || !Number.isFinite(latencyMs) || latencyMs < 0) {
throw new Error("routing record v2 latencyMs must be a non-negative number");
}
const providerMetadata = input.providerMetadata === void 0 || input.providerMetadata === null ? void 0 : (() => {
if (!input.providerMetadata || typeof input.providerMetadata !== "object" || Array.isArray(input.providerMetadata)) {
throw new Error("routing providerMetadata must be an object");
}
const entries = Object.entries(input.providerMetadata);
if (entries.length > MAX_PROVIDER_METADATA_FIELDS) {
throw new Error(`routing providerMetadata may carry at most ${MAX_PROVIDER_METADATA_FIELDS} fields`);
}
const normalized = {};
for (const [key, field] of entries) {
if (typeof key !== "string" || key.length > 64 || /prompt|body|content|message/i.test(key) || typeof field !== "string" && typeof field !== "number" && typeof field !== "boolean") {
throw new Error("routing providerMetadata values must be bounded strings, numbers, or booleans; raw bodies are rejected");
}
normalized[key] = typeof field === "string" ? field.slice(0, 200) : field;
}
return normalized;
})();
const record2 = {
schema: ROUTING_RECORD_V2_SCHEMA,
recordedAt: boundedString(input.recordedAt, "recordedAt", 64) ?? (/* @__PURE__ */ new Date()).toISOString(),
project: boundedString(input.project, "project", 128) ?? "",
runId: boundedString(input.runId, "runId", 128) ?? "",
stepId: boundedString(input.stepId, "stepId", 128) ?? "",
assignmentId: boundedString(input.assignmentId, "assignmentId", 128) ?? "",
attemptId: boundedString(input.attemptId, "attemptId", 128) ?? "",
harness: boundedString(input.harness, "harness", 64) ?? "",
provider: boundedString(input.provider, "provider", 64) ?? "",
requestedModel: normalizeModel(boundedString(input.requestedModel, "requestedModel", 200)) ?? "",
effectiveModel: normalizeModel(boundedString(input.effectiveModel, "effectiveModel", 200)) ?? "",
behavioralSha256,
latencyMs,
costBasis,
costUsd,
retries: boundedInt(input.retries, "retries") ?? 0
};
if (input.thinking !== void 0 && input.thinking !== null) {
record2.thinking = boundedString(input.thinking, "thinking", 64);
}
const rawRole = input.agentRole ?? input.role;
if (rawRole !== void 0 && rawRole !== null) {
record2.agentRole = boundedString(rawRole, "agentRole", 64);
}
if (input.contextTokens !== void 0) {
record2.contextTokens = boundedInt(input.contextTokens, "contextTokens") ?? null;
}
if (input.tokensIn !== void 0) {
record2.tokensIn = boundedInt(input.tokensIn, "tokensIn") ?? null;
}
if (input.tokensOut !== void 0) {
record2.tokensOut = boundedInt(input.tokensOut, "tokensOut") ?? null;
}
if (input.cacheReadTokens !== void 0) {
record2.cacheReadTokens = boundedInt(input.cacheReadTokens, "cacheReadTokens") ?? null;
}
if (input.cacheWriteTokens !== void 0) {
record2.cacheWriteTokens = boundedInt(input.cacheWriteTokens, "cacheWriteTokens") ?? null;
}
if (input.priceRef !== void 0 && input.priceRef !== null) {
record2.priceRef = boundedString(input.priceRef, "priceRef", 128);
}
if (input.verifierOutcome !== void 0 && input.verifierOutcome !== null) {
if (input.verifierOutcome !== "passed" && input.verifierOutcome !== "warning" && input.verifierOutcome !== "failed") {
throw new Error("routing verifierOutcome must be passed, warning, or failed");
}
record2.verifierOutcome = input.verifierOutcome;
}
if (input.finalOutcome !== void 0 && input.finalOutcome !== null) {
record2.finalOutcome = typeof input.finalOutcome === "string" ? input.finalOutcome.slice(0, 64) : void 0;
}
if (input.transitions !== void 0) {
record2.transitions = boundedInt(input.transitions, "transitions");
}
if (input.humanInterventions !== void 0) {
record2.humanInterventions = boundedInt(input.humanInterventions, "humanInterventions");
}
if (providerMetadata !== void 0) {
record2.providerMetadata = providerMetadata;
}
return record2;
}
function computeDecayedWeight(recordedAt, halfLifeDays = 14, now = Date.now()) {
const ts = typeof recordedAt === "number" ? recordedAt : Date.parse(recordedAt);
if (!Number.isFinite(ts)) return 1;
const deltaMs = Math.max(0, now - ts);
const halfLifeMs = halfLifeDays * 24 * 60 * 60 * 1e3;
return Math.pow(2, -deltaMs / halfLifeMs);
}
// plugins/kxm/src/engine.ts
var trustedProducers = /* @__PURE__ */ new WeakSet();
var CAPABILITY_PREFIX = "kxm-attempt-capability\0";
function createKxmSimulatedProducer(script) {
const producer = Object.freeze({
id: "driver-simulated",
async produce(request) {
const start = Date.now();
try {
const raw = await script(request);
const latencyMs = typeof raw.latencyMs === "number" ? raw.latencyMs : Math.max(0, Date.now() - start);
return {
costBasis: "unmetered",
tokensIn: null,
tokensOut: null,
cacheReadTokens: null,
cacheWriteTokens: null,
...raw,
latencyMs
};
} catch (error) {
return Promise.reject(error);
}
}
});
trustedProducers.add(producer);
return producer;
}
function registerTrustedProducer(producer) {
trustedProducers.add(producer);
}
function requireTrustedProducer(producer) {
if (!trustedProducers.has(producer)) {
throw runtimeError("engine_producer_untrusted", "producer", "producer is not a trusted factory instance");
}
}
function hashCapabilitySecret(secret) {
return `sha256:${createHash15("sha256").update(`${CAPABILITY_PREFIX}${secret}`, "utf8").digest("hex")}`;
}
function mintKxmCapabilitySecret() {
const secret = `kxmcap_${randomBytes2(32).toString("base64url")}`;
return { secret, hash: hashCapabilitySecret(secret) };
}
function mintCapabilitySecret() {
return mintKxmCapabilitySecret();
}
function pinKxmCompiledPlan(context, bundle, runId, options) {
return context.eventStore.transaction(() => {
const run = requireRun(context, runId);
if (run.projectId !== context.projectId || run.homeRuntimeId !== context.homeRuntimeId) {
throw runtimeError("run_owner_mismatch", runId, "run is not owned by this runtime context");
}
if (String(bundle.project.value.id) !== run.projectId) {
throw runtimeError("run_owner_mismatch", runId, "bundle project does not match the run");
}
const workflow = lookupKxmResource(bundle.workflows.values(), run.workflowId, "workflow");
if (!workflow) throw runtimeError("run_workflow_unknown", run.workflowId, `workflow ${run.workflowId} does not exist in this project`);
const revisions = kxmPolicyRevisions(bundle, options);
if (revisions.configRevision !== run.configRevision || revisions.executorPolicyRevision !== run.executorPolicyRevision || revisions.toolPolicyRevision !== run.toolPolicyRevision || revisions.memoryRevision !== run.memoryRevision) {
throw runtimeError("run_revision_drift", runId, "bundle revisions do not match the accepted run");
}
const compiled = freezeKxmCompiledPlan(compileKxmWorkflow({
id: run.workflowId,
value: workflow.value,
...workflow.logicalPath !== void 0 ? { logicalPath: workflow.logicalPath } : {}
}));
const envelope2 = {
schema: KXM_RUN_PLAN_SCHEMA,
runId: run.runId,
projectId: run.projectId,
homeRuntimeId: run.homeRuntimeId,
workflowId: run.workflowId,
revisions: {
config: run.configRevision,
executorPolicy: run.executorPolicyRevision,
toolPolicy: run.toolPolicyRevision,
memory: run.memoryRevision
},
projectLimits: kxmProjectAdmissionLimits(bundle),
plan: compiled,
gates: pinnedGatesForCompiledPlan(compiled, bundle, context.projectRoot)
};
const runPlanHash = hashKxmRunPlanEnvelope(envelope2);
const existing = context.eventStore.runPlan(runId);
if (existing) {
if (existing.runPlanHash !== runPlanHash) {
throw runtimeError("run_plan_pinned", runId, "run already has a different pinned plan");
}
return { plan: compiled, runPlanHash, idempotent: true };
}
if (run.status !== "created") {
throw runtimeError("run_plan_pinned", runId, "a plan can only be pinned from created");
}
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "run.status_changed",
sequence,
payload: { status: "preparing", runPlanHash }
};
context.eventStore.insertRunPlan({
runId,
runPlanHash,
envelope: kxmCanonicalJson(envelope2),
pinnedSequence: sequence
});
context.eventStore.appendEvent(event);
const state = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, state, sequence);
context.eventStore.updateRunStatus(runId, "preparing", now);
return { plan: compiled, runPlanHash, idempotent: false, event };
});
}
function startKxmRun(context, runId, options = {}) {
return context.eventStore.transaction(() => {
const run = requireRun(context, runId);
const envelope2 = loadKxmRunPlanEnvelope(context.eventStore, run);
const unsupported = options.allowLimits ? void 0 : unsupportedLimit(envelope2);
const state = foldStoredKxmRun(context, run);
if (unsupported) {
return { state, handoff: unsupported };
}
if (state.status !== "preparing") {
return { state };
}
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "run.status_changed",
sequence,
payload: { status: "running" }
};
context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, next, sequence);
context.eventStore.updateRunStatus(runId, "running", now);
return { state: next };
});
}
async function driveAdmitted(context, runId, producer, token, options = {}) {
const run = requireRun(context, runId);
if (run.status === "preparing") {
const started = startKxmRun(context, runId, options);
if (started.handoff || isTerminalRunStatus(started.state.status)) return started;
}
let latest = { state: foldStoredKxmRun(context, requireRun(context, runId)) };
if (latest.state.status === "cancelling") {
latest = await stepLocked(context, runId, producer, token);
if (latest.handoff || isTerminalRunStatus(latest.state.status)) return latest;
}
while (latest.state.status === "running") {
const overBudget = cancelRunDurationIfExceeded(context, runId);
if (overBudget) return overBudget;
const before = context.eventStore.runState(runId)?.lastSequence;
latest = await stepLocked(context, runId, producer, token);
if (latest.handoff) return latest;
if (latest.state.status === "running") {
const after = context.eventStore.runState(runId)?.lastSequence;
if (after === before) {
throw runtimeError("run_events_illegal", runId, "drive made no progress");
}
}
}
return latest;
}
function newDriveId(runId, token, runtimeId, monotonicNs) {
return `drv_${createHash15("sha256").update(`${runId}\0${token}\0${runtimeId}\0${monotonicNs}`, "utf8").digest("hex").slice(0, 24)}`;
}
function driveErrorSummary(error) {
const raw = error instanceof KxmConfigError ? error.issues[0]?.code : void 0;
const className = raw && /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/.test(raw) ? raw : "drive-failure";
return { class: className, component: "engine", retryable: false };
}
function receiptHandoff(handoff) {
return {
reason: handoff.reason,
detail: handoff.detail,
...handoff.field !== void 0 ? { field: handoff.field } : {},
...handoff.stepId !== void 0 ? { stepId: handoff.stepId } : {},
...handoff.attemptId !== void 0 ? { attemptId: handoff.attemptId } : {}
};
}
function appendDriveOpened(context, runId, driveId, mode) {
return context.eventStore.transaction(() => {
const run = requireRun(context, runId);
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "run.drive_opened",
sequence,
payload: { driveId, mode }
};
context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, next, sequence);
return { sequence, occurredAt: now };
});
}
function recordDriveReceipt(context, session, closeInfo) {
if (isKxmRuntimeContextClosed(context)) return;
try {
const run = context.eventStore.run(session.runId);
if (!run) return;
const state = foldStoredKxmRun(context, run);
const events = context.eventStore.events(session.runId, 0, 1e6);
if (events.length === 0) return;
const opened = state.drive;
const openedEvent = opened ? events.find((event) => event.sequence === opened.openedSequence && event.eventType === "run.drive_opened") : events.find((event) => event.eventType === "run.drive_opened" && event.payload.driveId === session.driveId);
const last = events[events.length - 1];
const openedSequence = opened?.openedSequence ?? openedEvent?.sequence;
if (openedSequence === void 0) return;
const closedAt = (/* @__PURE__ */ new Date()).toISOString();
const receipt = {
schema: KXM_DRIVE_RECEIPT_SCHEMA,
driveId: session.driveId,
runId: session.runId,
projectId: run.projectId,
homeRuntimeId: session.homeRuntimeId,
mode: session.mode,
openedAt: openedEvent?.occurredAt ?? session.openedAt,
openedSequence,
closedAt,
lastSequence: last.sequence,
logHash: hashKxmDriveLog(events.filter((event) => event.sequence >= 1 && event.sequence <= last.sequence)),
settlement: {
kind: closeInfo.kind,
status: state.status,
reason: closeInfo.reason ?? state.terminalReason ?? "",
...closeInfo.kind === "handoff" && closeInfo.handoff ? { handoff: receiptHandoff(closeInfo.handoff) } : {},
...closeInfo.error !== void 0 ? { error: closeInfo.error } : {}
},
budget: driveReceiptBudget(context, run.runId, state, events, closedAt),
producer: { id: closeInfo.producerId, closed: closeInfo.producerClosed }
};
context.eventStore.insertDriveReceipt(receipt);
if (closeInfo.kind === "handoff") {
releaseKxmRun(context.eventStore.path, session.runId, session.token);
}
} catch {
}
}
function kxmDrivePollProjection(context, runId, state) {
if (!state.drive) return void 0;
const events = context.eventStore.events(runId, 0, 1e6);
const openedEvent = events.find((event) => event.sequence === state.drive.openedSequence);
let receipt = null;
let unreadable = false;
try {
receipt = context.eventStore.driveReceipt(state.drive.driveId) ?? null;
} catch {
unreadable = true;
}
const projection = {
driveId: state.drive.driveId,
mode: state.drive.mode,
openedAt: openedEvent?.occurredAt ?? "",
receipt: unreadable ? null : receipt,
verified: false
};
if (unreadable) {
projection.divergence = "receipt unreadable";
return projection;
}
if (!receipt) {
projection.divergence = "no receipt";
return projection;
}
const checked = verifyKxmDriveReceipt(receipt, events, state.status, {
runId,
driveId: state.drive.driveId
});
projection.verified = checked.verified;
if (checked.divergence !== void 0) projection.divergence = checked.divergence;
return projection;
}
function inflightAttemptId(state) {
const leftover = unreconciledPanelAttemptId(state);
if (leftover) return leftover;
if (state.currentStep?.attemptId) {
const located = kxmFoldPanelAttempt(state.currentStep, state.currentStep.attemptId);
const status = located?.attempt.status;
if (status === "starting" || status === "executing" || status === "settling") return state.currentStep.attemptId;
}
return void 0;
}
function recordExecutingUnrecordedFailure(context, runId, attemptId, stepId) {
context.eventStore.transaction(() => {
const run = requireRun(context, runId);
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "run.status_changed",
sequence,
payload: { status: "failed", reason: "executing_unrecorded", stepId }
};
context.eventStore.appendEvent(event);
context.eventStore.settleCapability(attemptId, "revoked");
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, next, sequence);
context.eventStore.updateRunStatus(runId, "failed", now);
});
}
function recordBareDriveFailure(context, runId) {
if (isKxmRuntimeContextClosed(context)) return;
try {
const run = context.eventStore.run(runId);
if (!run) return;
const state = foldStoredKxmRun(context, run);
if (isTerminalRunStatus(state.status) || state.status === "cancelling") return;
const inflight = inflightAttemptId(state);
if (inflight) {
const currentStep = state.currentStep;
const located = kxmFoldPanelAttempt(currentStep, inflight);
if (currentStep && currentStep.panel.order.length === 1 && located?.attempt.status === "starting") {
const plan = rehydrateKxmCompiledPlanFromStore(context.eventStore, run);
const step = plan.steps[currentStep.stepId];
if (step?.kind === "gate") return;
if (step && (step.kind === "agent" || step.kind === "moa") && step.assignments.maximum > 1) return;
recordExecutingUnrecordedFailure(context, runId, inflight, currentStep.stepId);
}
return;
}
cancelKxmRun(context, runId, { reason: "drive_error" });
} catch {
}
}
async function closeDriveProducer(producer) {
if (typeof producer.close !== "function") return;
try {
await producer.close();
} catch {
}
}
var KxmRunScheduler = class _KxmRunScheduler {
context;
bundle;
configRevision;
constructor(context, bundle) {
this.context = context;
this.bundle = bundle;
this.configRevision = bundle.configRevision;
}
static for(context, bundle) {
if (String(bundle.project.value.id) !== context.projectId) {
throw runtimeError("run_owner_mismatch", context.projectId, "scheduler bundle project does not match the runtime context");
}
const limits = kxmProjectAdmissionLimits(bundle);
bindKxmSchedulerPolicy(context.eventStore.path, limits.maxConcurrentRuns, bundle.configRevision);
return new _KxmRunScheduler(context, bundle);
}
enqueue(runId, producer, options = {}) {
requireTrustedProducer(producer);
const policy = kxmSchedulerPolicy(this.context.eventStore.path);
if (!policy || policy.configRevision !== this.configRevision) {
return Promise.reject(runtimeError("scheduler_policy_conflict", runId, "scheduler handle does not match the active policy"));
}
try {
const run = requireRun(this.context, runId);
const envelope2 = loadKxmRunPlanEnvelope(this.context.eventStore, run);
return enqueueKxmScheduledRun(
this.context.eventStore.path,
runId,
envelope2.revisions.config,
envelope2.projectLimits.maxConcurrentRuns,
(token) => driveAdmitted(this.context, runId, producer, token, options)
);
} catch (error) {
return Promise.reject(error);
}
}
openDriveSession(runId, options) {
const policy = kxmSchedulerPolicy(this.context.eventStore.path);
if (!policy || policy.configRevision !== this.configRevision) {
return Promise.reject(runtimeError("scheduler_policy_conflict", runId, "scheduler handle does not match the active policy"));
}
try {
const run = requireRun(this.context, runId);
if (isTerminalRunStatus(run.status)) {
return Promise.reject(runtimeError("run_busy", runId, `run ${runId} is already ${run.status}`));
}
} catch (error) {
return Promise.reject(error);
}
const limits = kxmProjectAdmissionLimits(this.bundle);
const driveOptions = {
liveMode: options.liveMode ?? options.mode === "live"
};
if (options.allowLimits !== void 0) driveOptions.allowLimits = options.allowLimits;
let opened = false;
const pending = {
resolve: (_value) => void 0,
reject: (_error) => void 0
};
const settled = new Promise((resolve15, reject) => {
pending.resolve = resolve15;
pending.reject = reject;
});
void settled.then(void 0, () => void 0);
return new Promise((resolveOpen, rejectOpen) => {
const queued = enqueueKxmScheduledRun(
this.context.eventStore.path,
runId,
this.configRevision,
limits.maxConcurrentRuns,
async (token) => {
let producer;
try {
producer = options.createProducer();
requireTrustedProducer(producer);
const current = requireRun(this.context, runId);
if (current.status === "created") {
pinKxmCompiledPlan(this.context, this.bundle, runId);
}
const started = startKxmRun(this.context, runId, driveOptions);
if (started.handoff) {
const error = runtimeError("run_handoff_required", runId, started.handoff.detail);
Object.assign(error, { handoff: started.handoff });
throw error;
}
const driveId = newDriveId(runId, token, this.context.homeRuntimeId, kxmMonotonicNs());
const openedMeta = appendDriveOpened(this.context, runId, driveId, options.mode);
const startedState = foldStoredKxmRun(this.context, requireRun(this.context, runId));
const deadlineAt = driveDeadlineAt(this.context, runId, startedState);
const session = {
driveId,
runId,
token,
homeRuntimeId: this.context.homeRuntimeId,
mode: options.mode,
openedAt: openedMeta.occurredAt,
producerId: producer.id,
controller: new AbortController(),
settled,
...deadlineAt !== void 0 ? { deadlineAt } : {}
};
attachKxmDriveSession(this.context.eventStore.path, runId, token, session);
opened = true;
resolveOpen({ driveId, settled });
try {
const result = await driveAdmitted(this.context, runId, producer, token, driveOptions);
const kind = result.handoff ? "handoff" : isTerminalRunStatus(result.state.status) ? "terminal" : "unsettled";
recordDriveReceipt(this.context, session, {
kind,
...result.state.terminalReason !== void 0 ? { reason: result.state.terminalReason } : result.handoff ? { reason: result.handoff.reason } : {},
...result.handoff ? { handoff: result.handoff } : {},
producerId: producer.id,
producerClosed: false
});
pending.resolve(result);
return result;
} catch (error) {
recordBareDriveFailure(this.context, runId);
let foldedStatus;
try {
foldedStatus = foldStoredKxmRun(this.context, requireRun(this.context, runId)).status;
} catch {
foldedStatus = void 0;
}
recordDriveReceipt(this.context, session, {
kind: foldedStatus !== void 0 && isTerminalRunStatus(foldedStatus) ? "terminal" : "unsettled",
error: driveErrorSummary(error),
producerId: producer.id,
producerClosed: false
});
pending.reject(error);
throw error;
}
} finally {
if (producer) await closeDriveProducer(producer);
clearKxmDriveSession(this.context.eventStore.path, runId, token);
}
}
);
void queued.then(void 0, (error) => {
if (!opened) {
rejectOpen(error);
}
});
});
}
};
var attemptFallback = /* @__PURE__ */ new Map();
var runStickyRoute = /* @__PURE__ */ new Map();
function observeProducerFailure(error, capability) {
try {
const raw = error instanceof Error ? error.message : error;
const message = typeof raw === "string" ? raw : "";
let text = message;
if (capability) text = text.split(capability).join("[redacted]");
text = text.replace(/kxmcap_[A-Za-z0-9_-]+/g, "[redacted]");
const match = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){1,3}/.exec(text);
const extracted = match?.[0] ?? "";
const code = extracted.length > 0 && extracted.length <= 64 ? extracted : "producer_error";
const record2 = error && typeof error === "object" ? error : void 0;
const statusValue = record2?.statusCode ?? record2?.status ?? record2?.httpStatus;
const httpStatus = typeof statusValue === "number" && Number.isInteger(statusValue) ? statusValue : void 0;
const name = error instanceof Error ? error.name : void 0;
const sessionCarry = parseSessionCarry(record2?.sessionCarry);
return {
code,
failure: {
classified: classifyRouteFailure({ code, text: text.slice(0, 500), httpStatus, name }),
...sessionCarry ? { sessionCarry } : {}
}
};
} catch {
return { code: "producer_error", failure: { classified: classifyRouteFailure({ code: "producer_error" }) } };
}
}
function invokeProducer(producer, request) {
let pending;
try {
pending = Promise.resolve(producer.produce(request));
} catch (error) {
const observed = observeProducerFailure(error, request.capability);
return Promise.resolve({ error: true, errorCode: observed.code, failure: observed.failure });
}
return pending.then(
(result) => ({ result, error: false }),
(error) => {
const observed = observeProducerFailure(error, request.capability);
return { error: true, errorCode: observed.code, failure: observed.failure };
}
);
}
function stickyRouteFromEvents(context, runId) {
const remembered = runStickyRoute.get(runId);
if (remembered) return remembered;
let found;
for (const event of context.eventStore.events(runId, 0, 1e5)) {
if (event.eventType !== "routing.attempt.recorded") continue;
const routing = event.payload.routing;
const route = routing?.providerMetadata?.fallbackRoute;
if (typeof route === "string" && route.length > 0) found = route;
}
return found;
}
function stickyWalkRoute(context, step, agentId, runId, liveWrite) {
const loaded = loadAgentFallback(context.projectRoot, agentId, { liveWrite });
if (!loaded || loaded.policy.revert !== "never") return void 0;
const sticky = stickyRouteFromEvents(context, runId);
if (!sticky) return void 0;
const candidate = loaded.chain.find((item) => item.routeId === sticky);
if (!candidate) return void 0;
return candidateToRoute(candidate, loaded.roleId);
}
function candidateToRoute(candidate, role) {
return {
provider: candidate.provider,
model: candidate.model,
selector: candidate.selector,
harness: candidate.harness,
routeId: candidate.routeId,
role,
permissions: [...candidate.permissions],
...candidate.effort ? { effort: candidate.effort } : {}
};
}
function rememberAttemptFallback(attemptId, loaded, index, basePrompt) {
if (loaded.chain.length < 2 || loaded.policy.onError.length === 0 || loaded.policy.maxSwitches <= 0) return;
if (index < 0 || index >= loaded.chain.length) return;
attemptFallback.set(attemptId, {
policy: loaded.policy,
chain: loaded.chain,
index,
switches: 0,
basePrompt
});
}
function appendRouteSwitch(context, member, routeSwitch) {
const run = requireRun(context, member.run.runId);
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(run.runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "routing.route_switched",
sequence,
payload: {
attemptId: member.attemptId,
stepId: member.stepId,
routeSwitch: {
from: routeSwitch.from,
to: routeSwitch.to,
reason: routeSwitch.reason,
...routeSwitch.effort ? { effort: routeSwitch.effort } : {}
}
}
};
context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, sequence);
try {
context.logger?.({
event: "route_switch",
runId: run.runId,
attemptId: member.attemptId,
stepId: member.stepId,
from: routeSwitch.from,
to: routeSwitch.to,
reason: routeSwitch.reason,
...routeSwitch.effort ? { effort: routeSwitch.effort } : {}
});
} catch {
}
}
async function produceWithRouteFallback(context, member, producer) {
const session = attemptFallback.get(member.attemptId);
let request = member.request;
let produced = await invokeProducer(producer, request);
if (!session) return producerOutcome(produced);
let carry;
while (produced.error) {
const current = session.chain[session.index];
if (!current) break;
const failure = produced.failure?.classified ?? classifyRouteFailure({ code: produced.errorCode, text: produced.errorCode });
const decision = decideRouteSwitch({
policy: session.policy,
chain: session.chain,
currentRouteId: current.routeId,
switchesUsed: session.switches,
failure,
...current.effort || member.request.thinking ? { currentEffort: current.effort ?? member.request.thinking } : {}
});
if (decision.action !== "switch") break;
appendRouteSwitch(context, member, {
from: current.routeId,
to: decision.to.routeId,
reason: decision.reason,
...decision.effort ? { effort: decision.effort } : {}
});
session.switches += 1;
session.index = session.chain.findIndex((candidate) => candidate.routeId === decision.to.routeId);
carry = mergeSessionCarry(carry, produced.failure?.sessionCarry);
request = {
...member.request,
prompt: carryForwardPrompt(session.basePrompt, carry),
model: decision.to.model,
provider: decision.to.provider,
harness: decision.to.harness,
...decision.effort ? { thinking: decision.effort } : {}
};
produced = await invokeProducer(producer, request);
}
if (!produced.error && session.switches > 0 && session.policy.revert === "never") {
const route = session.chain[session.index];
if (route) {
session.stickyRouteId = route.routeId;
runStickyRoute.set(member.run.runId, route.routeId);
}
}
return producerOutcome(produced);
}
function producerOutcome(produced) {
return {
error: produced.error,
...produced.result !== void 0 ? { result: produced.result } : {},
...produced.errorCode !== void 0 ? { errorCode: produced.errorCode } : {}
};
}
var kxmGateDispatchSeams = {};
function peekDispatchContextSources(context, runId) {
if (!dispatchContextPresent(context.projectRoot)) return EMPTY_DISPATCH_SOURCES;
let run;
try {
run = requireRun(context, runId);
const state = foldStoredKxmRun(context, run);
const plan = rehydrateKxmCompiledPlanFromStore(context.eventStore, run);
if (state.status !== "running" || state.currentStep) return NOT_LOADED_DISPATCH_SOURCES;
const next = plan.steps[state.pendingStepId ?? plan.entryStepId];
if (next?.kind !== "agent" && next?.kind !== "moa") return NOT_LOADED_DISPATCH_SOURCES;
} catch {
return NOT_LOADED_DISPATCH_SOURCES;
}
return loadDispatchContextSources({
projectRoot: context.projectRoot,
projectId: run.projectId,
pinnedMemoryRevision: run.memoryRevision
});
}
async function stepLocked(context, runId, producer, token) {
const dispatchSources = peekDispatchContextSources(context, runId);
const prepared = context.eventStore.transaction(() => prepareDispatch(context, runId, producer.id, dispatchSources));
if (prepared.kind === "return") {
return prepared.handoff ? { state: prepared.state, handoff: prepared.handoff } : { state: prepared.state };
}
if (prepared.kind === "gate") {
const step = prepared.envelope.plan.steps[prepared.stepId];
if (!step || step.kind !== "gate") {
throw runtimeError("run_events_illegal", prepared.run.runId, "prepared gate step is not a gate");
}
const definition = prepared.envelope.gates.definitions[step.gate];
if (definition?.kind === "command") {
return runPreparedCommandGate(context, prepared, definition, token);
}
if (!definition || definition.kind !== "artifacts-exist") {
throw runtimeError("run_events_illegal", prepared.run.runId, "prepared gate is not artifacts-exist");
}
registerKxmAttemptController(context.eventStore.path, runId, { attemptId: prepared.attemptId, controller: prepared.controller });
const clearBudget = armRunDurationBudgetTimer(context, runId);
try {
const observation = evaluateArtifactsGate(context, definition);
kxmGateDispatchSeams.afterEvaluate?.(prepared);
return context.eventStore.transaction(() => settlePreparedGate(context, prepared, observation));
} finally {
clearBudget();
unregisterKxmAttemptController(context.eventStore.path, runId, prepared.attemptId);
}
}
return drivePanel(context, prepared.panel, producer);
}
async function runPreparedCommandGate(context, prepared, definition, token) {
assertCommandSeatbelt(definition.argv.join(" "));
const storePath = context.eventStore.path;
const observer = createCommandObserver({
definition,
cwd: context.projectRoot,
signal: prepared.controller.signal,
onSpawned: () => {
if (isKxmRuntimeContextClosed(context)) return;
try {
context.eventStore.transaction(() => {
recordGateSpawnedInTransaction(context, prepared.run, prepared.envelope, prepared.stepId);
kxmGateDispatchSeams.afterSpawnRecord?.(prepared);
});
} catch (error) {
try {
markKxmGateHoldUnsettled(storePath, prepared.run.runId, token, prepared.attemptId);
} catch {
}
throw error;
}
}
});
armKxmGateHold(storePath, prepared.run.runId, token, prepared.attemptId, () => observer.requestStop("cancel"));
registerKxmAttemptController(storePath, prepared.run.runId, { attemptId: prepared.attemptId, controller: prepared.controller });
const clearBudget = armRunDurationBudgetTimer(context, prepared.run.runId);
const unhookClose = registerKxmRuntimeCloseHook(context, () => {
try {
markKxmGateHoldUnsettled(storePath, prepared.run.runId, token, prepared.attemptId);
} catch {
}
dropKxmGateStopHook(storePath, prepared.run.runId, prepared.attemptId);
observer.beginBoundedCleanup();
});
try {
kxmGateDispatchSeams.beforeCommandSpawn?.(prepared);
const outcome = await observer.run();
dropKxmGateStopHook(storePath, prepared.run.runId, prepared.attemptId);
if (isKxmRuntimeContextClosed(context)) {
try {
markKxmGateHoldUnsettled(storePath, prepared.run.runId, token, prepared.attemptId);
} catch {
}
return closedCommandHandoff(context, prepared, outcome.kind === "uncertain" ? outcome.reason : "lost-close");
}
if (outcome.kind === "no-start") {
return commitOwnedCommandSettlement(context, prepared, token, () => recordGateNoStartInTransaction(context, prepared.run, prepared.envelope, prepared.stepId, outcome.observation), outcome.observation);
}
if (outcome.kind === "complete") {
try {
kxmGateDispatchSeams.beforeCommandSettle?.(prepared);
} catch (error) {
return recoverCommandRecordingFailure(context, prepared, token, outcome.observation, error);
}
if (isKxmRuntimeContextClosed(context)) {
try {
markKxmGateHoldUnsettled(storePath, prepared.run.runId, token, prepared.attemptId);
} catch {
}
return closedCommandHandoff(context, prepared, "lost-close");
}
return commitOwnedCommandSettlement(context, prepared, token, () => settlePreparedGate(context, prepared, outcome.observation), outcome.observation);
}
return commitCommandUncertainty(context, prepared, token, outcome.reason, outcome.observation);
} finally {
unhookClose();
clearBudget();
unregisterKxmAttemptController(storePath, prepared.run.runId, prepared.attemptId);
}
}
function closedCommandHandoff(context, prepared, reason) {
let state;
try {
state = foldStoredKxmRun(context, requireRun(context, prepared.run.runId));
} catch {
state = prepared.state;
}
return {
state,
handoff: {
reason: "attempt_unsettled",
stepId: prepared.stepId,
attemptId: prepared.attemptId,
detail: reason
}
};
}
function commitOwnedCommandSettlement(context, prepared, token, write, observation) {
let committed;
try {
committed = context.eventStore.transaction(() => write());
} catch (error) {
return recoverCommandRecordingFailure(context, prepared, token, observation, error);
}
try {
kxmGateDispatchSeams.afterSettlementCommit?.(prepared);
} catch (error) {
return retainCommittedCommandProof(context, prepared, token, error);
}
try {
finishKxmOwnedGate(context.eventStore.path, prepared.run.runId, token, prepared.attemptId);
} catch (error) {
return retainCommittedCommandProof(context, prepared, token, error);
}
return committed;
}
function retainCommittedCommandProof(context, prepared, token, error) {
try {
finishOwnedGateAfterCommittedTerminalProof(context, prepared, token);
} catch {
}
throw error;
}
function finishOwnedGateAfterCommittedTerminalProof(context, prepared, token) {
if (isKxmRuntimeContextClosed(context)) return;
const run = context.eventStore.run(prepared.run.runId);
if (!run || run.projectId !== context.projectId || run.homeRuntimeId !== context.homeRuntimeId) return;
const row = context.eventStore.gateAttempt(prepared.attemptId);
const preparedIdentity = {
runId: prepared.run.runId,
attemptId: prepared.attemptId,
assignmentId: prepared.assignmentId,
effectId: prepared.effectId,
stepId: prepared.stepId
};
if (!row || !gateRowIdentityMatches(row, preparedIdentity) || row.projectId !== context.projectId || row.homeRuntimeId !== context.homeRuntimeId) {
return;
}
const observation = context.eventStore.gateObservationForAttempt(prepared.attemptId);
const evidence = context.eventStore.gateEvidenceForAttempt(prepared.attemptId);
const events = context.eventStore.events(prepared.run.runId, 0, 1e6);
let state;
try {
state = foldStoredKxmRun(context, run);
} catch {
return;
}
const capability = context.eventStore.capabilityByAttempt(prepared.attemptId);
if (!capability || capability.state !== "settled" || capability.runId !== prepared.run.runId || capability.attemptId !== prepared.attemptId || capability.assignmentId !== prepared.assignmentId || capability.stepId !== prepared.stepId || capability.stepAttempt !== prepared.stepAttempt) {
return;
}
const terminalProof = isEvaluatedSettledProof(row, observation, evidence) || isExcludedTerminalProof(state, row, observation, evidence, events);
if (!terminalProof) return;
const hold = kxmGateHold(context.eventStore.path, prepared.run.runId);
const admittedToken = kxmAdmittedToken(context.eventStore.path, prepared.run.runId);
if (!hold || hold.state !== "active" || hold.attemptId !== prepared.attemptId || hold.token !== token || admittedToken !== token) {
return;
}
finishKxmOwnedGate(context.eventStore.path, prepared.run.runId, token, prepared.attemptId);
}
function recoverCommandRecordingFailure(context, prepared, token, observation, error) {
markKxmGateHoldUnsettled(context.eventStore.path, prepared.run.runId, token, prepared.attemptId);
if (isKxmRuntimeContextClosed(context)) {
throw error;
}
const existing = context.eventStore.gateObservationForAttempt(prepared.attemptId);
if (existing) {
throw runtimeError(
"run_events_illegal",
prepared.run.runId,
`command observation recording failed after committed proof: ${error instanceof Error ? error.message : String(error)}`
);
}
const folded = foldStoredKxmRun(context, requireRun(context, prepared.run.runId));
if (folded.currentStep?.attemptId === prepared.attemptId && folded.currentStep.observationId) {
throw runtimeError(
"run_events_illegal",
prepared.run.runId,
"command observation recording failed after committed proof"
);
}
const incomplete = {
...observation,
completeness: "incomplete",
errorClass: observation.errorClass ?? "recording-error",
stopCause: observation.stopCause === "none" ? "error" : observation.stopCause
};
return commitCommandUncertainty(context, prepared, token, "recording-error", incomplete, error);
}
function commitCommandUncertainty(context, prepared, token, reason, observation, priorError) {
try {
markKxmGateHoldUnsettled(context.eventStore.path, prepared.run.runId, token, prepared.attemptId);
} catch {
}
if (isKxmRuntimeContextClosed(context)) {
if (priorError) throw priorError;
return closedCommandHandoff(context, prepared, reason);
}
const existing = context.eventStore.gateObservationForAttempt(prepared.attemptId);
if (existing) {
throw runtimeError(
"run_events_illegal",
prepared.run.runId,
"command observation already committed; uncertainty cannot replace it"
);
}
const incomplete = { ...observation, completeness: "incomplete" };
try {
const written = context.eventStore.transaction(() => {
const result = recordGateUncertainInTransaction(context, prepared.run, prepared.envelope, prepared.stepId, reason, incomplete);
kxmGateDispatchSeams.afterUncertaintyWrite?.(prepared);
return result;
});
return {
state: written.state,
handoff: {
reason: "attempt_unsettled",
stepId: prepared.stepId,
attemptId: prepared.attemptId,
detail: reason
}
};
} catch (error) {
if (priorError) throw priorError;
throw error;
}
}
var kxmPanelDispatchSeams = {};
function readYamlFile(file) {
return readModelDocument(file);
}
function readModelDocument(file) {
if (!existsSync15(file)) return void 0;
try {
const parsed = (0, import_yaml11.parse)(readFileSync13(file, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
return parsed;
} catch {
return void 0;
}
}
function unreconciledPanelAttemptId(state) {
const current = state.currentStep;
if (!current) return void 0;
for (const assignmentId of current.panel.order) {
const assignment = current.panel.assignments[assignmentId];
if (!assignment) continue;
for (const [attemptId, attempt] of Object.entries(assignment.attempts)) {
if (attempt.status === "starting" || attempt.status === "executing" || attempt.status === "settling") {
return attemptId;
}
}
}
return void 0;
}
function resolveProducerRoute(projectRoot, step, agentId) {
if ((step.kind === "agent" || step.kind === "moa") && step.model !== void 0) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: "producer_route_unsupported: agent step model is not honored"
}
};
}
const agentFile = findYamlBasename(join18(projectRoot, ".kxm", "agents"), agentId, "agent") ?? agentId;
const agent = readYamlFile(join18(projectRoot, ".kxm", "agents", `${agentFile}.yaml`));
const role = typeof agent?.role === "string" ? agent.role : "";
if (!role) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: "producer_route_unsupported: agent has no role"
}
};
}
const roleDoc = readYamlFile(join18(projectRoot, ".kxm", "roles", `${role}.yaml`));
const roster = Array.isArray(roleDoc?.roster) ? roleDoc.roster : void 0;
if (!roster) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: role '${role}' has no roster`
}
};
}
const policy = loadRoutePolicy(projectRoot);
for (const entry of roster) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record2 = entry;
if (typeof record2.route !== "string" || record2.route.length === 0) continue;
const routeFile = findYamlBasename(join18(projectRoot, ".kxm", "models"), record2.route, "route") ?? record2.route;
const modelPath = join18(projectRoot, ".kxm", "models", `${routeFile}.yaml`);
const doc = readModelDocument(modelPath);
if (!doc) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: model file '.kxm/models/${record2.route}.yaml' is missing or unreadable`
}
};
}
if (doc.status !== "admitted") continue;
const modelName = typeof doc.model === "string" ? doc.model : "";
const vendor = typeof doc.vendor === "string" ? doc.vendor : "";
const harness = typeof doc.harness === "string" ? doc.harness : "";
if (!modelName || !vendor || !harness) continue;
const candidates = [modelName, `${vendor}/${modelName}`, `${harness}/${modelName}`];
const admittedSelector2 = candidates.find((candidate) => policy.admitted.includes(candidate));
const disabledSelector = candidates.find((candidate) => policy.disabled.includes(candidate));
if (!admittedSelector2 && disabledSelector) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: first admitted route '${record2.route}' for role '${role}' is disabled`
}
};
}
const selector = admittedSelector2 ?? (modelName.includes("/") ? modelName : `${vendor}/${modelName}`);
if (policy.disabled.includes(selector)) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: first admitted route '${record2.route}' for role '${role}' is disabled`
}
};
}
if (!policy.admitted.includes(selector)) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: model '${selector}' is not admitted`
}
};
}
const slash = selector.indexOf("/");
if (slash <= 0 || slash === selector.length - 1) {
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: invalid selector '${selector}'`
}
};
}
const permissions = Array.isArray(doc.permissions) ? doc.permissions.filter((item) => typeof item === "string") : [];
return {
provider: selector.slice(0, slash),
model: selector.slice(slash + 1),
selector,
harness,
routeId: routeFile,
role,
permissions,
...typeof record2.effort === "string" ? { effort: record2.effort } : {}
};
}
return {
error: {
reason: "step_unsupported",
field: "model",
detail: `producer_route_unsupported: role '${role}' has no admitted route`
}
};
}
function projectAgentStepTimeoutMs(context, run) {
return loadKxmRunPlanEnvelope(context.eventStore, run).projectLimits.agentStepTimeoutMs ?? KXM_DEFAULT_AGENT_STEP_TIMEOUT_MS;
}
function unsupportedAgentStepTimeout(step, limitMs) {
if (step.kind !== "agent" && step.kind !== "moa") return void 0;
if (step.timeoutMs === void 0 || step.timeoutMs <= limitMs) return void 0;
return {
reason: "step_unsupported",
field: "timeoutMs",
detail: "step timeoutMs is wider than project limits.agentStepTimeoutMs"
};
}
function narrowerPermission(left, right) {
return left === "read-only" || right === "read-only" ? "read-only" : "edit";
}
function stepRepositoryPermission(step) {
return Object.values(step.repositories).some((access) => access === "write") ? "edit" : "read-only";
}
function stepAccessDetail(step) {
const entries = Object.entries(step.repositories);
if (entries.length === 0) return "none";
return entries.map(([id, access]) => `${id} ${access}`).sort((left, right) => left < right ? -1 : left > right ? 1 : 0).join(", ");
}
function yamlToolsPreset(doc) {
const tools = doc?.tools;
if (!tools || typeof tools !== "object" || Array.isArray(tools)) return void 0;
const preset = tools.preset;
return typeof preset === "string" && preset.length > 0 ? preset : void 0;
}
function resolveToolDispatch(projectRoot, step, agentId) {
const stepPermission = stepRepositoryPermission(step);
if (step.kind !== "agent" && step.kind !== "moa") return { permission: stepPermission };
const agentFile = findYamlBasename(join18(projectRoot, ".kxm", "agents"), agentId, "agent") ?? agentId;
const agent = readYamlFile(join18(projectRoot, ".kxm", "agents", `${agentFile}.yaml`));
const roleId = typeof agent?.role === "string" ? agent.role : "";
if (!roleId) return { permission: stepPermission };
const roleDoc = readYamlFile(join18(projectRoot, ".kxm", "roles", `${roleId}.yaml`));
const rawPermission = roleDoc?.permission;
const rolePermission = rawPermission === "edit" || rawPermission === "read-only" ? rawPermission : void 0;
if (!rolePermission) return { permission: stepPermission };
const rolePreset = yamlToolsPreset(roleDoc);
const agentPreset = yamlToolsPreset(agent);
const rolePresetProfile = rolePreset ? toolPresetProfile(rolePreset) : void 0;
if (rolePreset && rolePresetProfile === "edit" && rolePermission === "read-only") {
return {
error: {
reason: "step_unsupported",
field: "tools.preset",
detail: `tools.preset ${rolePreset} exceeds role ${roleId} permission read-only`
}
};
}
if (agentPreset) {
const exceeds = toolPresetExceedsRoleMessage(agentPreset, roleId, rolePermission, rolePreset);
if (exceeds) {
return { error: { reason: "step_unsupported", field: "tools.preset", detail: exceeds } };
}
}
let chain = rolePermission;
if (rolePresetProfile) chain = narrowerPermission(chain, rolePresetProfile);
const agentProfile = agentPreset ? toolPresetProfile(agentPreset) : void 0;
if (agentProfile) chain = narrowerPermission(chain, agentProfile);
const permission = narrowerPermission(chain, stepPermission);
if (stepPermission === "edit" && permission === "read-only") {
return {
error: {
reason: "step_unsupported",
field: "permission",
detail: `role permission ${rolePermission} resolves to ${chain}; step access ${stepAccessDetail(step)}`
}
};
}
return { permission };
}
function executingSingletonAttempt(plan, state) {
const current = state.currentStep;
if (!current || current.panel.order.length !== 1) return void 0;
const step = plan.steps[current.stepId];
if (!step || step.kind !== "agent" && step.kind !== "moa" || step.assignments.maximum > 1) return void 0;
const attemptId = unreconciledPanelAttemptId(state);
if (!attemptId) return void 0;
const located = kxmFoldPanelAttempt(current, attemptId);
if (located?.attempt.status !== "executing") return void 0;
return { stepId: current.stepId, assignmentId: located.assignmentId, attemptId };
}
function settleExitedExecutingAttempt(context, run, executing) {
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(run.runId);
let mono = kxmMonotonicNs();
const events = [];
const push2 = (eventType, payload) => {
events.push({
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
});
mono = kxmIncrementMonotonicNs(mono);
};
push2("attempt.status_changed", { attemptId: executing.attemptId, status: "settling" });
push2("assignment.result_recorded", {
assignmentId: executing.assignmentId,
resultClass: "producer_rejected",
status: "result_recorded",
producerError: "executing_unrecorded",
reason: "executing_unrecorded"
});
push2("attempt.status_changed", { attemptId: executing.attemptId, status: "terminal" });
push2("assignment.terminal", { assignmentId: executing.assignmentId, outcome: "failed", status: "terminal" });
push2("step.status_changed", { stepId: executing.stepId, status: "cancelled", previousStatus: "running" });
push2("run.status_changed", { status: "cancelled", reason: cancelReasonFromLog2(context, run.runId) });
for (const event of events) context.eventStore.appendEvent(event);
context.eventStore.settleCapability(executing.attemptId, "settled");
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(run.runId, "cancelled", now);
return next;
}
function prepareDispatch(context, runId, producerId, dispatchSources) {
const run = requireRun(context, runId);
const plan = rehydrateKxmCompiledPlanFromStore(context.eventStore, run);
const state = foldStoredKxmRun(context, run);
if (kxmPanelDispatchSeams.skipDispatch?.()) {
return { kind: "return", state };
}
if (state.status === "cancelling" && kxmAttemptControllers(context.eventStore.path, runId).length === 0) {
const executing = executingSingletonAttempt(plan, state);
if (executing) {
const exited = readOneShotObservedChildExit(runId, executing.attemptId);
if (exited === true) {
return { kind: "return", state: settleExitedExecutingAttempt(context, run, executing) };
}
return {
kind: "return",
state,
handoff: {
reason: "attempt_unreconciled",
stepId: executing.stepId,
attemptId: executing.attemptId,
detail: "issued attempt is not held by this process"
}
};
}
return {
kind: "return",
state,
handoff: {
reason: "cancel_pending_foreign",
detail: "cancellation is pending in another process",
...state.currentStep?.attemptId ? { attemptId: state.currentStep.attemptId } : {}
}
};
}
const unreconciledAttemptId = unreconciledPanelAttemptId(state);
if (unreconciledAttemptId) {
const currentStepId = state.currentStep?.stepId;
if (currentStepId === void 0) {
throw runtimeError("run_events_illegal", runId, "unreconciled attempt is missing step identity");
}
return {
kind: "return",
state,
handoff: {
reason: "attempt_unreconciled",
attemptId: unreconciledAttemptId,
stepId: currentStepId,
detail: "issued attempt is not held by this process"
}
};
}
if (state.status === "blocked_uncertain") {
return {
kind: "return",
state,
handoff: {
reason: "gate_uncertain_blocked",
...state.currentStep?.stepId ? { stepId: state.currentStep.stepId } : {},
...state.currentStep?.attemptId ? { attemptId: state.currentStep.attemptId } : {},
detail: "run is blocked_uncertain awaiting external signal or operator intervention"
}
};
}
if (state.status !== "running" || state.currentStep) {
if (state.currentStep?.effectState === "blocked_uncertain") {
return {
kind: "return",
state,
handoff: {
reason: "attempt_unsettled",
stepId: state.currentStep.stepId,
...state.currentStep.attemptId ? { attemptId: state.currentStep.attemptId } : {},
detail: "step effect is blocked_uncertain"
}
};
}
return { kind: "return", state };
}
const stepId = state.pendingStepId ?? plan.entryStepId;
const step = plan.steps[stepId];
if (!step) throw runtimeError("run_events_illegal", runId, `unknown pending step ${stepId}`);
const allEvents = context.eventStore.events(runId, 0, 1e5);
let accumulatedMeteredCost = 0;
let unmeteredOrUnknownAttempts = 0;
for (const ev of allEvents) {
if (ev.eventType === "routing.attempt.recorded") {
const routing = ev.payload?.routing;
if (routing?.costBasis === "metered" && typeof routing.costUsd === "number") {
accumulatedMeteredCost += routing.costUsd;
} else if (routing?.costBasis === "unmetered" || routing?.costBasis === "unknown") {
unmeteredOrUnknownAttempts += 1;
}
}
}
if (plan.limits.maxModelCost !== void 0 && accumulatedMeteredCost >= plan.limits.maxModelCost) {
return { kind: "return", ...failBudget(context, run, plan, state, "budget_model_cost", stepId) };
}
const maxUnmeteredAttempts = 100;
if (unmeteredOrUnknownAttempts >= maxUnmeteredAttempts) {
return { kind: "return", ...failBudget(context, run, plan, state, "budget_unmetered_attempts", stepId) };
}
if (step.kind === "gate") {
const envelope2 = loadKxmRunPlanEnvelope(context.eventStore, run);
const unsupported2 = unsupportedGateStep(plan, step, envelope2, context);
if (unsupported2) return { kind: "return", state, handoff: { ...unsupported2, stepId } };
const definition = envelope2.gates.definitions[step.gate];
if (definition?.kind === "command") {
const preflightResult = gateRecoveryPreflight(context);
const firstBlocking = preflightResult.blocking[0];
if (firstBlocking) {
return {
kind: "return",
state,
handoff: {
reason: "gate_recovery_pending",
attemptId: firstBlocking.attemptId,
detail: `${preflightResult.blocking.length} unfinished gate attempt(s) in project`
}
};
}
}
const result = recordGateIntentInTransaction(context, run, envelope2, stepId);
const current = result.state.currentStep;
const attemptId = current?.attemptId;
const assignmentId = current?.assignmentId;
const effectId = current?.effectId;
if (!current || current.stepId !== stepId || attemptId === void 0 || assignmentId === void 0 || effectId === void 0) {
throw runtimeError("run_events_illegal", runId, "gate intent did not bind exact attempt identity");
}
return {
kind: "gate",
run,
envelope: envelope2,
stepId,
stepAttempt: current.stepAttempt,
assignmentId,
attemptId,
effectId,
controller: new AbortController(),
state: result.state
};
}
const unsupported = unsupportedStep(plan, step, producerId);
if (unsupported) return { kind: "return", state, handoff: { ...unsupported, stepId } };
const wideTimeout = unsupportedAgentStepTimeout(step, projectAgentStepTimeoutMs(context, run));
if (wideTimeout) return { kind: "return", state, handoff: { ...wideTimeout, stepId } };
const firstListed = step.assignments.allowedAgents[0];
const firstAgentId = step.kind === "agent" || step.kind === "moa" ? firstListed ? firstListed : step.agent : void 0;
if (firstAgentId) {
const toolDispatch = resolveToolDispatch(context.projectRoot, step, firstAgentId);
if ("error" in toolDispatch) {
return { kind: "return", state, handoff: { ...toolDispatch.error, stepId } };
}
}
let resolvedRoute;
if (producerId !== "driver-simulated") {
const agentId = firstAgentId ?? (step.kind === "agent" || step.kind === "moa" ? step.agent : "coordinator");
const routeResult = resolveProducerRoute(context.projectRoot, step, agentId);
if ("error" in routeResult) {
return { kind: "return", state, handoff: { ...routeResult.error, stepId } };
}
resolvedRoute = routeResult;
const stickyRoute = stickyWalkRoute(
context,
step,
agentId,
run.runId,
Object.values(step.repositories).some((access) => access === "write")
);
if (stickyRoute && stickyRoute.routeId !== resolvedRoute.routeId) resolvedRoute = stickyRoute;
const writeRefusal = unsupportedLiveWrite(
context.projectRoot,
step,
resolvedRoute,
loadKxmRunPlanEnvelope(context.eventStore, run).projectLimits.maxConcurrentRuns
);
if (writeRefusal) return { kind: "return", state, handoff: { ...writeRefusal, stepId } };
}
const used = state.stepAttempts[stepId] ?? 0;
if (used >= step.maxAttempts) {
return { kind: "return", ...failBudget(context, run, plan, state, "budget_step_attempts", stepId) };
}
const stepAttempt = used + 1;
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(runId);
let mono = kxmMonotonicNs();
const events = [];
const push2 = (eventType, payload) => {
events.push({
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
});
mono = kxmIncrementMonotonicNs(mono);
};
push2("step.entered", { stepId, stepAttempt, status: "pending" });
push2("step.status_changed", { stepId, status: "preparing", previousStatus: "pending" });
for (const event of events) context.eventStore.appendEvent(event);
const entered = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, entered, events[events.length - 1].sequence);
const firstBirth = birthMember(context, {
run,
plan,
step,
stepId,
stepAttempt,
enterRunning: true,
producerId,
resolvedRoute,
dispatchSources
});
if ("handoff" in firstBirth) {
return { kind: "return", state: entered, handoff: firstBirth.handoff };
}
const first = firstBirth;
return {
kind: "panel",
panel: {
run,
plan,
step,
stepId,
stepAttempt,
target: step.assignments.target,
maxParallel: step.assignments.maxParallel,
first,
state: first.state,
dispatchSources
}
};
}
function panelInFlight(state) {
const current = state.currentStep;
if (!current) return 0;
let count = 0;
for (const assignmentId of current.panel.order) {
const assignment = current.panel.assignments[assignmentId];
if (!assignment) continue;
for (const attempt of Object.values(assignment.attempts)) {
if (attempt.status === "starting" || attempt.status === "executing" || attempt.status === "settling") count += 1;
}
}
return count;
}
function panelFrozenState(state) {
const current = state.currentStep;
if (!current) return true;
return current.outcome !== void 0 || current.status === "passed" || current.status === "failed" || current.status === "cancelled";
}
function birthAllowed(state, step) {
if (state.status !== "running" || state.cancelRequested || panelFrozenState(state)) return false;
const born = state.currentStep?.panel.order.length ?? 0;
if (born >= step.assignments.target) return false;
if (panelInFlight(state) >= step.assignments.maxParallel) return false;
return true;
}
function birthMember(context, input) {
const run = requireRun(context, input.run.runId);
const folded = foldStoredKxmRun(context, run);
if (!birthAllowed(folded, input.step)) {
throw runtimeError("run_events_illegal", run.runId, "member birth is not legal");
}
const promptText = context.eventStore.getRunPrompt(run.runId);
if (promptText === void 0) {
throw runtimeError("run_prompt_mismatch", run.runId, "prompt text missing from accepted run prompt store");
}
const promptHash = createHash15("sha256").update(promptText, "utf8").digest("hex");
const expectedHash = run.promptSha256.replace(/^sha256:/, "");
if (promptHash !== expectedHash) {
throw runtimeError("run_prompt_mismatch", run.runId, "prompt text does not match accepted promptSha256");
}
const born = folded.currentStep?.panel.order.length ?? 0;
const allowed = input.step.assignments.allowedAgents;
const agentId = allowed && allowed.length > born && allowed[born] ? allowed[born] : input.step.kind === "agent" || input.step.kind === "moa" ? input.step.agent : "coordinator";
const toolDispatch = resolveToolDispatch(context.projectRoot, input.step, agentId);
if ("error" in toolDispatch) {
return { handoff: { ...toolDispatch.error, stepId: input.stepId } };
}
let resolvedRoute = input.resolvedRoute;
if (!resolvedRoute && input.producerId && input.producerId !== "driver-simulated") {
const routeResult = resolveProducerRoute(context.projectRoot, input.step, agentId);
if ("error" in routeResult) {
return { handoff: { ...routeResult.error, stepId: input.stepId } };
}
resolvedRoute = routeResult;
}
const liveProducer = Boolean(input.producerId && input.producerId !== "driver-simulated");
const liveWrite = liveProducer && Object.values(input.step.repositories).some((access) => access === "write");
const loadedFallback = loadAgentFallback(context.projectRoot, agentId, { liveWrite });
let fallbackIndex = -1;
if (loadedFallback && loadedFallback.chain.length > 1 && loadedFallback.policy.maxSwitches > 0) {
const sticky = loadedFallback.policy.revert === "never" ? stickyRouteFromEvents(context, run.runId) : void 0;
const stickyIndex = sticky ? loadedFallback.chain.findIndex((candidate) => candidate.routeId === sticky) : -1;
if (!resolvedRoute) {
fallbackIndex = stickyIndex > 0 ? stickyIndex : 0;
const start = loadedFallback.chain[fallbackIndex];
if (start) resolvedRoute = candidateToRoute(start, loadedFallback.roleId);
} else if (stickyIndex > 0 && resolvedRoute.routeId !== loadedFallback.chain[stickyIndex]?.routeId) {
const start = loadedFallback.chain[stickyIndex];
if (start) {
resolvedRoute = candidateToRoute(start, loadedFallback.roleId);
fallbackIndex = stickyIndex;
}
} else {
fallbackIndex = loadedFallback.chain.findIndex((candidate) => candidate.routeId === resolvedRoute?.routeId);
}
}
const dispatchContext = assembleDispatchContext(input.dispatchSources, {
projectId: run.projectId,
runId: run.runId,
stepId: input.stepId,
agentId,
task: [input.step.instructions, promptText].filter((part) => typeof part === "string" && part.trim().length > 0).join("\n\n")
});
const assignmentId = newKxmAssignmentId();
const attemptId = newKxmAttemptId();
const minted = mintCapabilitySecret();
const controller = new AbortController();
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(run.runId);
let mono = kxmMonotonicNs();
const events = [];
const push2 = (eventType, payload) => {
events.push({
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
});
mono = kxmIncrementMonotonicNs(mono);
};
push2("assignment.created", { assignmentId, stepId: input.stepId, stepAttempt: input.stepAttempt, agentId, status: "created" });
push2("assignment.accepted", { assignmentId, status: "accepted" });
push2("attempt.created", { attemptId, assignmentId, status: "created" });
push2("assignment.dispatched", {
assignmentId,
capabilityHash: minted.hash,
status: "dispatched",
...resolvedRoute ? { model: { provider: resolvedRoute.provider, model: resolvedRoute.model } } : {}
});
push2("attempt.status_changed", { attemptId, status: "starting" });
if (input.enterRunning) {
push2("step.status_changed", { stepId: input.stepId, status: "running", previousStatus: "preparing" });
}
for (const event of events) context.eventStore.appendEvent(event);
context.eventStore.insertCapability({
attemptId,
runId: run.runId,
assignmentId,
stepId: input.stepId,
stepAttempt: input.stepAttempt,
producerId: input.producerId ?? "driver-simulated",
capabilityHash: minted.hash,
state: "issued"
});
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, events[events.length - 1].sequence);
const rawContextPacket = buildFormalContextPacket({
project: run.projectId,
targetRole: agentId,
task: {
taskId: run.runId,
stepId: input.stepId,
stepAttempt: input.stepAttempt,
objective: promptText,
allowedOutcomes: [...input.step.outcomes],
permissionCeiling: toolDispatch.permission
},
acceptanceCriteria: input.step.requiredEvidence.map((ev) => ({
id: ev.key,
description: `Provide ${ev.kind} evidence for ${ev.key}`,
verificationKind: "witness",
required: true
})),
plan: {
planHash: input.plan.planHash?.stageId ?? "default",
activeStepIndex: input.step.index,
totalSteps: input.plan.order.length,
settledDecisions: []
},
...dispatchContext.items.length > 0 ? { arbitratedItems: dispatchContext.items } : {},
...dispatchContext.unresolvedGaps.length > 0 ? { unresolvedGaps: dispatchContext.unresolvedGaps } : {}
});
const { packet: contextPacket } = pruneContextPacket(rawContextPacket);
const generatedPrompt = formatContextPacketForPrompt(contextPacket);
const member = {
run,
plan: input.plan,
step: input.step,
stepId: input.stepId,
stepAttempt: input.stepAttempt,
assignmentId,
attemptId,
agentId,
capabilityHash: minted.hash,
producerId: input.producerId ?? "driver-simulated",
request: {
runId: run.runId,
stepId: input.stepId,
stepAttempt: input.stepAttempt,
assignmentId,
attemptId,
agentId,
instanceNo: born + 1,
scopeEpoch: 1,
capability: minted.secret,
allowedOutcomes: input.step.outcomes,
signal: controller.signal,
prompt: input.step.instructions ? `${input.step.instructions}
${generatedPrompt}` : generatedPrompt,
permission: toolDispatch.permission,
...(input.step.kind === "agent" || input.step.kind === "moa") && input.step.timeoutMs !== void 0 ? { timeoutMs: input.step.timeoutMs } : {},
contextPacket,
...resolvedRoute?.effort !== void 0 ? { thinking: resolvedRoute.effort } : {},
...resolvedRoute ? { harness: resolvedRoute.harness, provider: resolvedRoute.provider, model: resolvedRoute.model } : {}
},
controller,
state: next
};
if (input.dispatchSources.present && context.logger) {
try {
context.logger({
event: "dispatch_context_assembled",
runId: run.runId,
stepId: input.stepId,
stepAttempt: input.stepAttempt,
agentId,
role: dispatchContext.role,
deliveredIds: dispatchContext.deliveredIds,
renderDeferred: dispatchContext.renderDeferred,
provenanceSummary: dispatchContext.audit?.provenanceSummary ?? {},
estimatedTokens: dispatchContext.audit?.estimatedTokens ?? 0,
budgetTokens: dispatchContext.audit?.budgetTokens ?? null,
skippedUnboundScopes: input.dispatchSources.skippedUnboundScopes,
unresolvedGaps: dispatchContext.unresolvedGaps
});
} catch {
}
}
if (loadedFallback && fallbackIndex >= 0) {
rememberAttemptFallback(attemptId, loadedFallback, fallbackIndex, member.request.prompt ?? "");
}
kxmPanelDispatchSeams.afterBirth?.(member);
return member;
}
function appendExecuting(context, dispatch) {
const run = requireRun(context, dispatch.run.runId);
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(dispatch.run.runId);
let mono = kxmMonotonicNs();
const events = [
{
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType: "assignment.executing",
sequence: sequence++,
payload: { assignmentId: dispatch.assignmentId, status: "executing" }
},
{
...kxmEventBase(context, run, now, kxmIncrementMonotonicNs(mono)),
eventId: newKxmEventId(),
eventType: "attempt.status_changed",
sequence: sequence++,
payload: { attemptId: dispatch.attemptId, status: "executing" }
}
];
for (const event of events) context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, events[events.length - 1].sequence);
}
function singletonPanel(step) {
return step.assignments.maximum === 1 && step.assignments.target === 1;
}
function unreconciledHandoff(state, stepId, attemptId) {
return {
state,
handoff: {
reason: "attempt_unreconciled",
stepId,
...attemptId !== void 0 ? { attemptId } : {},
detail: "issued attempt is not held by this process"
}
};
}
function capabilityHashBound(stored, minted) {
const left = Buffer.from(stored);
const right = Buffer.from(minted);
return left.length === right.length && timingSafeEqual(left, right);
}
function capabilityMatchesDispatch(capability, member, allowedStates, expectedProducerId) {
return Boolean(
capability && capabilityHashBound(capability.capabilityHash, member.capabilityHash) && capability.runId === member.run.runId && capability.stepId === member.stepId && capability.stepAttempt === member.stepAttempt && capability.assignmentId === member.assignmentId && capability.attemptId === member.attemptId && capability.producerId === (expectedProducerId ?? member.producerId ?? "driver-simulated") && allowedStates.includes(capability.state)
);
}
async function drivePanel(context, panel, producer) {
const runId = panel.run.runId;
const owned = /* @__PURE__ */ new Map();
const pending = /* @__PURE__ */ new Map();
let stopBirths = false;
let settlementFailed = false;
const budgetClears = /* @__PURE__ */ new Map();
const register = (member) => {
registerKxmAttemptController(context.eventStore.path, runId, { attemptId: member.attemptId, controller: member.controller });
budgetClears.set(member.attemptId, armRunDurationBudgetTimer(context, runId));
owned.set(member.attemptId, member);
};
const abortOwned = () => {
for (const member of owned.values()) member.controller.abort();
};
const launch = (member) => {
register(member);
const work = (async () => {
try {
kxmPanelDispatchSeams.beforeAppendExecuting?.(member);
const started = context.eventStore.transaction(() => {
if (kxmPanelDispatchSeams.failAppendExecuting?.(member)) {
throw runtimeError("run_events_illegal", runId, "appendExecuting failed");
}
const run = requireRun(context, runId);
const state = foldStoredKxmRun(context, run);
const capability = context.eventStore.capabilityByAttempt(member.attemptId);
const located = kxmFoldPanelAttempt(state.currentStep, member.attemptId);
if (state.cancelRequested || state.status === "cancelling" || !capabilityMatchesDispatch(capability, member, ["issued"], producer.id) || !located || located.assignmentId !== member.assignmentId || located.attempt.status !== "starting") {
return false;
}
appendExecuting(context, member);
return true;
});
if (!started) return { attemptId: member.attemptId, invoked: false, skipped: true };
const executingBound = () => {
const run = requireRun(context, runId);
const state = foldStoredKxmRun(context, run);
const capability = context.eventStore.capabilityByAttempt(member.attemptId);
const located = kxmFoldPanelAttempt(state.currentStep, member.attemptId);
if (state.cancelRequested || state.status === "cancelling" || !capabilityMatchesDispatch(capability, member, ["issued"], producer.id) || !located || located.assignmentId !== member.assignmentId || located.attempt.status !== "executing") {
return false;
}
return true;
};
if (!executingBound()) return { attemptId: member.attemptId, invoked: false, skipped: true };
kxmPanelDispatchSeams.beforeInvoke?.(member);
if (!executingBound()) return { attemptId: member.attemptId, invoked: false, skipped: true };
const live = member.producerId !== "driver-simulated";
const writes = Object.values(member.step.repositories).some((access) => access === "write");
const before = live ? captureWorktreeWitness(context.projectRoot) : void 0;
const produced = await produceWithRouteFallback(context, member, producer);
if (live && produced.result && before) {
const after = captureWorktreeWitness(context.projectRoot);
return {
attemptId: member.attemptId,
invoked: true,
produced: { ...produced, result: applyAuthoringWitness(produced.result, { writes, before, after }) }
};
}
return { attemptId: member.attemptId, invoked: true, produced };
} catch (error) {
member.controller.abort();
return { attemptId: member.attemptId, invoked: false, appendFailed: true, error };
}
})();
pending.set(member.attemptId, work);
};
let routeHandoff;
const tryBirth = () => {
if (stopBirths || routeHandoff) return void 0;
return context.eventStore.transaction(() => {
const run = requireRun(context, runId);
const state = foldStoredKxmRun(context, run);
if (!birthAllowed(state, panel.step)) return void 0;
const born = birthMember(context, {
run,
plan: panel.plan,
step: panel.step,
stepId: panel.stepId,
stepAttempt: panel.stepAttempt,
producerId: producer.id,
dispatchSources: panel.dispatchSources
});
if ("handoff" in born) {
routeHandoff = born.handoff;
return void 0;
}
return born;
});
};
const settleInvoked = (member, produced) => {
if (produced.result?.effectUncertain) {
settlementFailed = true;
stopBirths = true;
return false;
}
try {
context.eventStore.transaction(() => {
if (kxmPanelDispatchSeams.failSettleMember?.(member)) {
throw runtimeError("run_events_illegal", runId, "member settlement write failed");
}
settleMember(context, member, produced.result, produced.error, produced.errorCode);
});
return true;
} catch (err) {
if (err instanceof Error && /costBasis/.test(err.message)) {
throw err;
}
settlementFailed = true;
stopBirths = true;
return false;
}
};
const drainPendingInvoked = async () => {
const rest = await Promise.allSettled([...pending.values()]);
pending.clear();
for (const result of rest) {
if (result.status !== "fulfilled") continue;
const item = result.value;
const sibling = owned.get(item.attemptId);
if (sibling && item.invoked) {
settleInvoked(sibling, item.produced);
}
}
};
try {
launch(panel.first);
while (true) {
while (!stopBirths && !settlementFailed) {
try {
const next = tryBirth();
if (routeHandoff) {
stopBirths = true;
break;
}
if (!next) break;
launch(next);
} catch {
stopBirths = true;
abortOwned();
await drainPendingInvoked();
const state = foldStoredKxmRun(context, requireRun(context, runId));
return unreconciledHandoff(state, panel.stepId);
}
}
if (routeHandoff) {
const handoff = routeHandoff;
abortOwned();
await drainPendingInvoked();
const state = foldStoredKxmRun(context, requireRun(context, runId));
return { state, handoff };
}
if (pending.size === 0) break;
const finished = await Promise.race(pending.values());
pending.delete(finished.attemptId);
const member = owned.get(finished.attemptId);
if (!member) continue;
if ("appendFailed" in finished && finished.appendFailed) {
stopBirths = true;
abortOwned();
const rest = await Promise.all([...pending.values()]);
pending.clear();
if (singletonPanel(panel.step)) {
context.eventStore.transaction(() => hardStopUnrecorded(context, member, "executing_unrecorded"));
throw finished.error;
}
for (const item of rest) {
const sibling = owned.get(item.attemptId);
if (sibling && item.invoked) {
settleInvoked(sibling, item.produced);
}
}
const state = foldStoredKxmRun(context, requireRun(context, runId));
return unreconciledHandoff(state, panel.stepId, member.attemptId);
}
if (!finished.invoked) {
stopBirths = true;
continue;
}
if (!settleInvoked(member, finished.produced)) {
abortOwned();
const rest = await Promise.all([...pending.values()]);
pending.clear();
for (const item of rest) {
const sibling = owned.get(item.attemptId);
if (sibling && item.invoked) {
settleInvoked(sibling, item.produced);
}
}
const state = foldStoredKxmRun(context, requireRun(context, runId));
return unreconciledHandoff(state, panel.stepId, member.attemptId);
}
}
const folded = foldStoredKxmRun(context, requireRun(context, runId));
const leftover = unreconciledPanelAttemptId(folded);
if (leftover || settlementFailed) {
return unreconciledHandoff(folded, panel.stepId, leftover);
}
const born = folded.currentStep?.panel.order.length ?? 0;
const allTerminal = Boolean(
folded.currentStep && born > 0 && folded.currentStep.panel.order.every((assignmentId) => folded.currentStep?.panel.assignments[assignmentId]?.status === "terminal") && kxmFoldPanelAttemptIds(folded.currentStep).every((attemptId) => kxmFoldPanelAttempt(folded.currentStep, attemptId)?.attempt.status === "terminal")
);
if (!allTerminal) {
return unreconciledHandoff(folded, panel.stepId, leftover);
}
if (born < panel.target && folded.status !== "cancelling" && !folded.cancelRequested) {
return unreconciledHandoff(folded, panel.stepId);
}
try {
return context.eventStore.transaction(() => joinPanel(context, panel));
} catch {
const state = foldStoredKxmRun(context, requireRun(context, runId));
return unreconciledHandoff(state, panel.stepId);
}
} catch (error) {
abortOwned();
await drainPendingInvoked();
throw error;
} finally {
for (const attemptId of owned.keys()) {
budgetClears.get(attemptId)?.();
unregisterKxmAttemptController(context.eventStore.path, runId, attemptId);
}
}
}
var ENGINE_ROUTING_METADATA_KEYS = /* @__PURE__ */ new Set(["workflowId", "askSha256", "objectiveSha256", "stepWrites"]);
var MAX_PRODUCER_ROUTING_METADATA_FIELDS = MAX_PROVIDER_METADATA_FIELDS - ENGINE_ROUTING_METADATA_KEYS.size;
function engineRoutingMetadata(dispatch, producer) {
const metadata = {};
if (producer !== void 0 && producer !== null) {
if (typeof producer !== "object" || Array.isArray(producer)) {
throw new Error("routing providerMetadata must be an object");
}
let kept = 0;
for (const [key, value] of Object.entries(producer)) {
if (kept >= MAX_PRODUCER_ROUTING_METADATA_FIELDS) break;
if (ENGINE_ROUTING_METADATA_KEYS.has(key)) continue;
metadata[key] = value;
kept += 1;
}
}
metadata.workflowId = dispatch.plan.workflowId;
metadata.askSha256 = kxmStepAskSha256(dispatch.plan, dispatch.stepId, dispatch.agentId);
metadata.objectiveSha256 = dispatch.run.promptSha256;
metadata.stepWrites = Object.values(dispatch.step.repositories).some((access) => access === "write");
const stickyRouteId = attemptFallback.get(dispatch.attemptId)?.stickyRouteId;
if (stickyRouteId && Object.keys(metadata).length < MAX_PROVIDER_METADATA_FIELDS) metadata.fallbackRoute = stickyRouteId;
return metadata;
}
function producerRoutingRecord(context, dispatch, result, now, finalOutcome) {
const run = requireRun(context, dispatch.run.runId);
if (result.costBasis === void 0 || result.costBasis === null) {
throw runtimeError("settle_missing_cost_basis", run.runId, `attempt settlement rejected: missing required costBasis for attempt ${dispatch.attemptId}`);
}
if (result.costBasis !== "metered" && result.costBasis !== "unmetered" && result.costBasis !== "unknown") {
throw runtimeError("settle_invalid_cost_basis", run.runId, `attempt settlement rejected: invalid costBasis ${String(result.costBasis)}`);
}
if (result.costBasis === "metered" && (typeof result.costUsd !== "number" || !Number.isFinite(result.costUsd) || result.costUsd < 0)) {
throw runtimeError("settle_invalid_cost", run.runId, "attempt settlement rejected: metered costBasis requires non-negative finite costUsd");
}
const envelope2 = loadKxmRunPlanEnvelope(context.eventStore, run);
const rawHash = result.behavioralSha256 ?? behavioralConfigHash({
requestedModel: result.requestedModel ?? "simulated",
effectiveModel: result.effectiveModel ?? result.requestedModel ?? "simulated",
agentRole: dispatch.step.kind === "agent" || dispatch.step.kind === "moa" ? dispatch.step.agent : void 0,
toolPolicyVersion: envelope2.revisions.toolPolicy
});
const record2 = {
schema: ROUTING_RECORD_V2_SCHEMA,
recordedAt: now,
project: run.projectId,
runId: run.runId,
stepId: dispatch.stepId,
assignmentId: dispatch.assignmentId,
attemptId: dispatch.attemptId,
harness: result.harness ?? (dispatch.producerId === "pi" ? "pi" : "driver-simulated"),
provider: result.provider ?? "simulated",
requestedModel: result.requestedModel ?? "simulated",
effectiveModel: result.effectiveModel ?? result.requestedModel ?? "simulated",
behavioralSha256: rawHash.startsWith("sha256:") ? rawHash : `sha256:${rawHash}`,
latencyMs: typeof result.latencyMs === "number" ? result.latencyMs : 0,
costBasis: result.costBasis,
costUsd: result.costUsd ?? null,
retries: Math.max(0, dispatch.stepAttempt - 1),
thinking: result.thinking ?? dispatch.request.thinking
};
for (const field of ["contextTokens", "tokensIn", "tokensOut", "cacheReadTokens", "cacheWriteTokens", "priceRef"]) {
if (result[field] !== void 0) record2[field] = result[field];
}
record2.agentRole = result.agentRole ?? dispatch.agentId;
record2.providerMetadata = engineRoutingMetadata(dispatch, result.providerMetadata);
if (finalOutcome !== void 0) record2.finalOutcome = finalOutcome;
return parseRoutingRecordV2(record2);
}
function settleMember(context, dispatch, result, produceError, produceErrorCode) {
const run = requireRun(context, dispatch.run.runId);
const state = foldStoredKxmRun(context, run);
const capability = context.eventStore.capabilityByAttempt(dispatch.attemptId);
const located = kxmFoldPanelAttempt(state.currentStep, dispatch.attemptId);
if (!located || located.assignmentId !== dispatch.assignmentId || located.attempt.status !== "executing" || !capability || !capabilityMatchesDispatch(capability, dispatch, ["issued", "revoked"])) {
throw runtimeError("run_events_illegal", run.runId, "settle attempted for a non-current capability");
}
const cancelling = state.status === "cancelling" || capability.state === "revoked";
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(run.runId);
let mono = kxmMonotonicNs();
const events = [];
const push2 = (eventType, payload) => {
events.push({
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
});
mono = kxmIncrementMonotonicNs(mono);
};
push2("attempt.status_changed", { attemptId: dispatch.attemptId, status: "settling" });
if (cancelling) {
push2("routing.attempt.recorded", { routing: producerRoutingRecord(
context,
dispatch,
result ?? { outcome: "cancelled", costBasis: "unknown", costUsd: null },
now
) });
push2("assignment.result_recorded", { assignmentId: dispatch.assignmentId, resultClass: "cancelled", status: "result_recorded" });
push2("attempt.status_changed", { attemptId: dispatch.attemptId, status: "terminal" });
push2("assignment.terminal", { assignmentId: dispatch.assignmentId, outcome: "cancelled", status: "terminal" });
} else if (produceError) {
const envelope2 = loadKxmRunPlanEnvelope(context.eventStore, run);
const rawHash = result?.behavioralSha256 ?? behavioralConfigHash({
requestedModel: result?.requestedModel ?? "simulated",
effectiveModel: result?.effectiveModel ?? result?.requestedModel ?? "simulated",
agentRole: dispatch.step.kind === "agent" || dispatch.step.kind === "moa" ? dispatch.step.agent : void 0,
toolPolicyVersion: envelope2.revisions.toolPolicy
});
const behavioralSha256 = rawHash.startsWith("sha256:") ? rawHash : `sha256:${rawHash}`;
const routingRecord = {
schema: ROUTING_RECORD_V2_SCHEMA,
recordedAt: now,
project: run.projectId,
runId: run.runId,
stepId: dispatch.stepId,
assignmentId: dispatch.assignmentId,
attemptId: dispatch.attemptId,
// Label the producer that actually ran: the old fallback printed "driver-simulated"
// for every producer that was not literally "pi", so a live oneshot drive that
// failed authentication read in the log as a simulation.
harness: result?.harness ?? dispatch.producerId,
provider: result?.provider ?? "simulated",
requestedModel: result?.requestedModel ?? "simulated",
effectiveModel: result?.effectiveModel ?? result?.requestedModel ?? "simulated",
behavioralSha256,
latencyMs: typeof result?.latencyMs === "number" ? result.latencyMs : 0,
costBasis: "unknown",
costUsd: null,
retries: Math.max(0, dispatch.stepAttempt - 1),
agentRole: dispatch.agentId,
finalOutcome: "failed",
providerMetadata: engineRoutingMetadata(dispatch)
};
push2("routing.attempt.recorded", { routing: parseRoutingRecordV2(routingRecord) });
push2("assignment.result_recorded", {
assignmentId: dispatch.assignmentId,
resultClass: "producer_rejected",
status: "result_recorded",
...produceErrorCode !== void 0 ? { producerError: produceErrorCode } : {}
});
push2("attempt.status_changed", { attemptId: dispatch.attemptId, status: "terminal" });
push2("assignment.terminal", { assignmentId: dispatch.assignmentId, outcome: "failed", status: "terminal" });
} else {
if (!result) {
throw runtimeError("settle_missing_cost_basis", run.runId, `attempt settlement rejected: missing required costBasis for attempt ${dispatch.attemptId}`);
}
const outcome = typeof result.outcome === "string" ? result.outcome : void 0;
const known = outcome !== void 0 && dispatch.step.outcomes.includes(outcome);
push2("routing.attempt.recorded", {
routing: producerRoutingRecord(
context,
dispatch,
result,
now,
known ? kxmAttemptFinalOutcome(dispatch.step, { resultClass: "outcome", outcome }) : "failed"
)
});
if (!known) {
push2("assignment.result_recorded", {
assignmentId: dispatch.assignmentId,
resultClass: "outcome_unknown",
status: "result_recorded"
});
push2("attempt.status_changed", { attemptId: dispatch.attemptId, status: "terminal" });
push2("assignment.terminal", { assignmentId: dispatch.assignmentId, outcome: "failed", status: "terminal" });
} else {
push2("assignment.result_recorded", {
assignmentId: dispatch.assignmentId,
outcome,
resultClass: "outcome",
status: "result_recorded"
});
push2("attempt.status_changed", { attemptId: dispatch.attemptId, status: "terminal" });
push2("assignment.terminal", { assignmentId: dispatch.assignmentId, outcome, status: "terminal" });
}
}
context.eventStore.settleCapability(dispatch.attemptId, "settled");
attemptFallback.delete(dispatch.attemptId);
for (const event of events) context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, events[events.length - 1].sequence);
}
function joinPanel(context, panel) {
const run = requireRun(context, panel.run.runId);
const state = foldStoredKxmRun(context, run);
const current = state.currentStep;
if (!current || current.stepId !== panel.stepId) {
throw runtimeError("run_events_illegal", run.runId, "join attempted without the prepared step");
}
const joined = kxmJoinAll(panel.step, current.panel);
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(run.runId);
let mono = kxmMonotonicNs();
const events = [];
const push2 = (eventType, payload) => {
events.push({
...kxmEventBase(context, run, now, mono),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
});
mono = kxmIncrementMonotonicNs(mono);
};
const failRun = (reason) => {
push2("step.status_changed", { stepId: panel.stepId, status: "failed", previousStatus: "running" });
push2("run.status_changed", { status: "failed", reason, stepId: panel.stepId });
for (const event of events) context.eventStore.appendEvent(event);
const next2 = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next2, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(run.runId, "failed", now);
return { state: next2 };
};
const cancelRun = () => {
push2("step.status_changed", { stepId: panel.stepId, status: "cancelled", previousStatus: "running" });
push2("run.status_changed", { status: "cancelled", reason: cancelReasonFromLog2(context, run.runId) });
for (const event of events) context.eventStore.appendEvent(event);
const next2 = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next2, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(run.runId, "cancelled", now);
return { state: next2 };
};
const members = [];
for (const assignmentId of current.panel.order) {
const assignment = current.panel.assignments[assignmentId];
const attemptId = assignment?.currentAttemptId;
const attempt = attemptId ? assignment?.attempts[attemptId] : void 0;
members.push({ resultClass: attempt?.resultClass, outcome: attempt?.outcome });
}
const rejected = members.some((member) => member.resultClass === "outcome_unknown" || member.resultClass === "producer_rejected");
const declared = members.filter((member) => member.resultClass === "outcome");
const declaredConflict = declared.length > 0 && declared.some((member) => member.outcome !== declared[0]?.outcome);
if (state.cancelRequested || state.status === "cancelling") {
if (rejected || declaredConflict) return failRun(rejected ? "outcome_unknown" : "join_conflict");
return cancelRun();
}
if (joined.tag === "rejected") return failRun("outcome_unknown");
if (joined.tag === "conflict") return failRun("join_conflict");
if (joined.tag === "cancelled") {
throw runtimeError("run_events_illegal", run.runId, "cancelled join requires cancellation authority");
}
if (joined.tag !== "outcome") {
throw runtimeError("run_events_illegal", run.runId, "join attempted before the panel is joinable");
}
const outcome = joined.outcome;
const selected = panel.step.transitions[outcome];
if (!selected) return failRun("outcome_unknown");
push2("step.outcome_recorded", { stepId: panel.stepId, stepAttempt: panel.stepAttempt, outcome });
const stepStatus = outcome === "passed" ? "passed" : outcome === "cancelled" ? "cancelled" : "failed";
push2("step.status_changed", { stepId: panel.stepId, status: stepStatus, previousStatus: "running" });
const budget = transitionBudgetFailure(panel.plan, state, panel.stepId, outcome);
if (budget) {
push2("run.status_changed", { status: "failed", reason: budget, stepId: panel.stepId, outcome });
for (const event of events) context.eventStore.appendEvent(event);
const next2 = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next2, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(run.runId, "failed", now);
return { state: next2 };
}
if (selected.to === "step") {
push2("step.transitioned", { fromStepId: panel.stepId, toStepId: selected.target, outcome });
} else {
push2("step.transitioned", { fromStepId: panel.stepId, status: selected.terminalStatus, outcome });
push2("run.status_changed", { status: selected.terminalStatus });
}
for (const event of events) context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(run.runId, next.status, now);
return { state: next };
}
function failBudget(context, run, plan, state, reason, stepId) {
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(run.runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "run.status_changed",
sequence,
payload: { status: "failed", reason, stepId }
};
context.eventStore.appendEvent(event);
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, sequence);
context.eventStore.updateRunStatus(run.runId, "failed", now);
void state;
return { state: next };
}
function hardStopUnrecorded(context, dispatch, reason) {
const run = requireRun(context, dispatch.run.runId);
const now = (/* @__PURE__ */ new Date()).toISOString();
const sequence = context.eventStore.nextSequence(run.runId);
const event = {
...kxmEventBase(context, run, now, kxmMonotonicNs()),
eventId: newKxmEventId(),
eventType: "run.status_changed",
sequence,
payload: { status: "failed", reason, stepId: dispatch.stepId }
};
context.eventStore.appendEvent(event);
context.eventStore.settleCapability(dispatch.attemptId, "revoked");
const next = foldStoredKxmRun(context, run);
persistKxmRunState(context, run.runId, next, sequence);
context.eventStore.updateRunStatus(run.runId, "failed", now);
}
function kxmTransitionBudgetFailure(plan, state, fromStepId, outcome) {
return transitionBudgetFailure(plan, state, fromStepId, outcome);
}
function transitionBudgetFailure(plan, state, fromStepId, outcome) {
const selected = plan.steps[fromStepId]?.transitions[outcome];
if (!selected) return "outcome_unknown";
const edgeKey = `${fromStepId}:${outcome}`;
const edgeUsed = (state.edgeTransitions[edgeKey] ?? 0) + 1;
if (selected.maxTransitions !== void 0 && edgeUsed > selected.maxTransitions) return "budget_edge";
if (state.transitionsUsed + 1 > plan.transitionBudget) return "budget_transitions";
if (selected.to === "step") {
const target = plan.steps[selected.target];
const used = state.stepAttempts[selected.target] ?? 0;
if (target && used >= target.maxAttempts) return "budget_step_attempts";
}
return void 0;
}
var MAX_TIMER_DELAY_MS = 2147483647;
function elapsedMsBetween(fromIso, toIso) {
const from = Date.parse(fromIso);
const to = Date.parse(toIso);
if (!Number.isFinite(from) || !Number.isFinite(to)) return 0;
return Math.max(0, Math.trunc(to - from));
}
function declaredRunDurationBudget(context, runId) {
const run = context.eventStore.run(runId);
if (!run) return void 0;
try {
const envelope2 = loadKxmRunPlanEnvelope(context.eventStore, run);
return effectiveRunDurationBudget(envelope2.plan.limits, envelope2.projectLimits);
} catch {
return void 0;
}
}
function budgetNowIso(context) {
if (process.env.KXM_DETERMINISTIC_TEST_CLOCK === "1" && context.budgetClock) return context.budgetClock();
return (/* @__PURE__ */ new Date()).toISOString();
}
function runDurationOverrunPayload(context, runId, nowIso2 = budgetNowIso(context)) {
const declared = declaredRunDurationBudget(context, runId);
if (!declared) return void 0;
const run = context.eventStore.run(runId);
if (!run) return void 0;
const state = foldStoredKxmRun(context, run);
if (!state.runningSince) return void 0;
if (isTerminalRunStatus(state.status) || state.status === "cancelling") return void 0;
const elapsedMs = elapsedMsBetween(state.runningSince, nowIso2);
if (elapsedMs < declared.budgetMs) return void 0;
return { budgetMs: declared.budgetMs, elapsedMs, source: declared.source };
}
function cancelRunDurationIfExceeded(context, runId) {
if (isKxmRuntimeContextClosed(context)) return void 0;
const payload = runDurationOverrunPayload(context, runId);
if (!payload) return void 0;
cancelKxmRun(context, runId, { reason: "budget_run_duration", budget: payload });
return { state: foldStoredKxmRun(context, requireRun(context, runId)) };
}
function driveDeadlineAt(context, runId, state) {
const declared = declaredRunDurationBudget(context, runId);
if (!declared || !state.runningSince) return void 0;
const start = Date.parse(state.runningSince);
if (!Number.isFinite(start)) return void 0;
return new Date(start + declared.budgetMs).toISOString();
}
function driveReceiptBudget(context, runId, state, events, closedAt) {
const declared = declaredRunDurationBudget(context, runId);
if (!declared) return null;
const elapsedMs = state.runningSince ? elapsedMsBetween(state.runningSince, closedAt) : 0;
const overrun = events.some((event) => event.eventType === "run.cancel_requested" && event.payload.reason === "budget_run_duration");
return {
budgetMs: declared.budgetMs,
source: declared.source,
elapsedMs,
overrun
};
}
function cancelReasonFromLog2(context, runId) {
const events = context.eventStore.events(runId, 0, 1e6);
for (let index = events.length - 1; index >= 0; index -= 1) {
const event = events[index];
if (event.eventType === "run.cancel_requested" && typeof event.payload.reason === "string") {
return event.payload.reason;
}
}
return "operator_cancel";
}
function armRunDurationBudgetTimer(context, runId) {
const declared = declaredRunDurationBudget(context, runId);
if (!declared) return () => void 0;
const run = context.eventStore.run(runId);
if (!run) return () => void 0;
const state = foldStoredKxmRun(context, run);
if (!state.runningSince) return () => void 0;
const startMs = Date.parse(state.runningSince);
if (!Number.isFinite(startMs)) return () => void 0;
const deadlineMs = startMs + declared.budgetMs;
let timer;
let cleared = false;
const fire = () => {
timer = void 0;
if (cleared || isKxmRuntimeContextClosed(context)) return;
const nowIso2 = budgetNowIso(context);
const elapsedMs = elapsedMsBetween(state.runningSince, nowIso2);
if (elapsedMs < declared.budgetMs) {
arm(declared.budgetMs - elapsedMs);
return;
}
try {
cancelKxmRun(context, runId, {
reason: "budget_run_duration",
budget: { budgetMs: declared.budgetMs, elapsedMs, source: declared.source }
});
} catch {
}
};
const arm = (remaining) => {
if (cleared) return;
const delay = Math.min(Math.max(0, remaining), MAX_TIMER_DELAY_MS);
timer = setTimeout(fire, delay);
timer.unref();
};
const unhook = registerKxmRuntimeCloseHook(context, () => {
cleared = true;
if (timer !== void 0) clearTimeout(timer);
timer = void 0;
});
arm(deadlineMs - Date.now());
return () => {
if (cleared) return;
cleared = true;
if (timer !== void 0) clearTimeout(timer);
timer = void 0;
unhook();
};
}
function unsupportedLimit(envelope2) {
if (envelope2.plan.limits.maxAgentTimeMs !== void 0) {
return { reason: "limit_unsupported", field: "limits.maxAgentTimeMs", detail: "agent-time budget enforcement is not available in this slice" };
}
if (envelope2.projectLimits.maxAgentTimeMs !== void 0) {
return { reason: "limit_unsupported", field: "project.limits.maxAgentTimeMs", detail: "agent-time budget enforcement is not available in this slice" };
}
return void 0;
}
function unsupportedStep(plan, step, producerId) {
if (step.kind === "gate") throw runtimeError("run_plan_corrupt", plan.workflowId, `unsupportedStep called on gate without envelope; use unsupportedGateStep instead`);
if (step.kind !== "agent" && step.kind !== "moa" && step.kind !== "approval" && step.kind !== "wait") {
return { reason: "step_unsupported", field: "kind", detail: `step kind ${step.kind} is not executed in this slice` };
}
if (step.assignments.maxAttemptsPerAssignment > 2) {
return { reason: "step_unsupported", field: "assignments.maxAttemptsPerAssignment", detail: "only up to two physical attempts are supported in this slice" };
}
if (step.join.strategy !== "all" && step.join.strategy !== "all-settled") {
return { reason: "step_unsupported", field: "join.strategy", detail: "only join all or all-settled is supported" };
}
if (step.join.strategy === "all" && step.join.minimumPassed !== void 0) {
return { reason: "step_unsupported", field: "join.minimumPassed", detail: "minimumPassed requires join strategy all-settled" };
}
if (step.join.cancelRemaining) {
return { reason: "step_unsupported", field: "join.cancelRemaining", detail: "cancelRemaining is not executed in this slice" };
}
if (step.assignments.distinctBy.some((d) => d !== "provider")) {
return { reason: "step_unsupported", field: "assignments.distinctBy", detail: "only distinctBy provider is supported in this slice" };
}
if (step.assignments.maxWriteRepositories !== void 0 && step.assignments.maxWriteRepositories > 1) {
return { reason: "step_unsupported", field: "assignments.maxWriteRepositories", detail: "at most one write repository is supported in this slice" };
}
for (const evidence of step.requiredEvidence) {
if (!evidence || !["artifact", "assignment-result", "gate", "approval", "receipt"].includes(evidence.kind)) {
return { reason: "step_unsupported", field: "requiredEvidence", detail: `evidence kind '${evidence?.kind}' is not supported in this slice` };
}
}
if (step.timeoutMs !== void 0 && step.timeoutMs <= 0) {
return { reason: "step_unsupported", field: "timeoutMs", detail: "timeoutMs must be positive" };
}
if (step.safeSpeculation) return { reason: "step_unsupported", field: "safeSpeculation", detail: "speculation is not executed in this slice" };
if (step.tools) return { reason: "step_unsupported", field: "tools", detail: "tools are not executed in this slice" };
if (step.secrets.length > 0) return { reason: "step_unsupported", field: "secrets", detail: "secrets are not executed in this slice" };
for (const [repoId, access] of Object.entries(step.repositories)) {
if (access !== "read" && access !== "write" && access !== "none") {
return { reason: "step_unsupported", field: "repositories", detail: `invalid repository access '${access}' on ${repoId}` };
}
}
return void 0;
}
function unsupportedLiveWrite(projectRoot, step, route, maxConcurrentRuns) {
if (!Object.values(step.repositories).some((access) => access === "write")) return void 0;
if (step.assignments.maximum !== 1) {
return {
reason: "step_unsupported",
field: "assignments.maximum",
detail: "live write steps run a single assignment; the checkout witness cannot attribute edits between writers"
};
}
if (maxConcurrentRuns !== 1) {
return {
reason: "step_unsupported",
field: "limits.maxConcurrentRuns",
detail: "live write steps require limits.maxConcurrentRuns of 1; concurrent runs share one checkout"
};
}
if (!oneShotWriterArgs(route.harness)) {
return {
reason: "step_unsupported",
field: "repositories",
detail: `live write steps require an audited writer profile; ${route.harness} has none`
};
}
const writerIds = listRoleBindings(projectRoot).writer;
if (!Array.isArray(writerIds) || writerIds.length === 0) {
return { reason: "step_unsupported", field: "model", detail: "writer roster has no admitted edit route" };
}
const named = writerIds.includes(route.routeId);
if (!named || !route.permissions.includes("edit")) {
return {
reason: "step_unsupported",
field: "model",
detail: `live write route ${route.selector} on ${route.harness} is not an admitted edit route on the writer roster`
};
}
return void 0;
}
function unsupportedGateStep(plan, step, envelope2, context) {
if (!step.gate) return { reason: "step_unsupported", field: "gate", detail: "gate step is missing gate id" };
if (envelope2.gates.registry === null) {
return { reason: "step_unsupported", field: "gate", detail: `step ${step.id} refers to a gate but registry is null` };
}
const definition = envelope2.gates.definitions[step.gate];
if (!definition) {
return { reason: "step_unsupported", field: "gate", detail: `gate definition ${step.gate} not found in registry` };
}
if (definition.kind === "reserved") {
return { reason: "gate_unsupported", field: "gate", detail: `gate ${step.gate} is reserved and cannot be executed` };
}
if (step.assignments.allowedAgents && step.assignments.allowedAgents.length > 0) {
return { reason: "step_unsupported", field: "assignments.allowedAgents", detail: "gate steps do not support allowedAgents" };
}
if (step.assignments.minimum !== 1 || step.assignments.target !== 1 || step.assignments.maximum !== 1) {
return { reason: "step_unsupported", field: "assignments", detail: "gate steps require exactly 1 agent assignment" };
}
if (step.assignments.maxParallel !== 1) {
return { reason: "step_unsupported", field: "assignments.maxParallel", detail: "gate steps require maxParallel of 1" };
}
if (step.assignments.maxAttemptsPerAssignment !== 1) {
return { reason: "step_unsupported", field: "assignments.maxAttemptsPerAssignment", detail: "gate steps require maxAttemptsPerAssignment of 1" };
}
if (step.assignments.distinctBy && step.assignments.distinctBy.length > 0) {
return { reason: "step_unsupported", field: "assignments.distinctBy", detail: "gate steps do not support distinctBy" };
}
if (step.assignments.maxWriteRepositories) {
return { reason: "step_unsupported", field: "assignments.maxWriteRepositories", detail: "gate steps do not support maxWriteRepositories" };
}
if (step.join.strategy !== "all") {
return { reason: "step_unsupported", field: "join", detail: `gate steps require join strategy 'all', not '${step.join.strategy}'` };
}
if (step.join.minimumPassed !== void 0) {
return { reason: "step_unsupported", field: "join", detail: "gate steps do not support minimumPassed" };
}
if (step.join.cancelRemaining) {
return { reason: "step_unsupported", field: "join", detail: "gate steps do not support cancelRemaining" };
}
for (const evidence of step.requiredEvidence) {
if (!evidence || !["gate", "artifact", "receipt", "assignment-result", "approval"].includes(evidence.kind)) {
return { reason: "step_unsupported", field: "requiredEvidence", detail: `gate steps do not support evidence kind '${evidence?.kind}'` };
}
}
if (step.safeSpeculation) {
return { reason: "step_unsupported", field: "safeSpeculation", detail: "gate steps do not support safeSpeculation" };
}
if (step.tools) {
return { reason: "step_unsupported", field: "tools", detail: "gate steps do not support tools" };
}
if (step.secrets && step.secrets.length > 0) {
return { reason: "step_unsupported", field: "secrets", detail: "gate steps do not support secrets" };
}
if (step.model) {
return { reason: "step_unsupported", field: "model", detail: "gate steps do not support model" };
}
if (plan.reproOracle?.stageId === step.id) {
return { reason: "step_unsupported", field: "reproOracle", detail: "gate steps cannot be repro oracle" };
}
if (plan.planHash?.stageId === step.id) {
return { reason: "step_unsupported", field: "planHash", detail: "gate steps cannot be plan hash oracle" };
}
if (step.timeoutMs !== void 0) {
if (definition.kind === "artifacts-exist") {
return { reason: "step_unsupported", field: "timeoutMs", detail: "artifacts-exist gates do not support timeoutMs" };
}
if (definition.kind === "command" && definition.timeoutMs !== void 0 && step.timeoutMs < definition.timeoutMs) {
return { reason: "step_unsupported", field: "timeoutMs", detail: "command step timeoutMs narrower than the registry timeout is refused" };
}
}
const repositories = step.repositories;
if (!repositories || Object.keys(repositories).length === 0) {
return { reason: "step_unsupported", field: "repositories", detail: "gate steps require repository declarations" };
}
if (definition.kind === "artifacts-exist") {
const controlAccess = repositories.control;
if (controlAccess !== "read" && controlAccess !== "write") {
return { reason: "step_unsupported", field: "repositories", detail: "artifacts-exist gates require control repository access as read or write" };
}
for (const [repoId, access] of Object.entries(repositories)) {
if (repoId !== "control" && access !== "none") {
return { reason: "step_unsupported", field: "repositories", detail: "artifacts-exist gates require other repositories to have access 'none'" };
}
}
} else if (definition.kind === "command") {
for (const [repoId, access] of Object.entries(repositories)) {
if (access !== "read" && access !== "write" && access !== "none") {
return { reason: "step_unsupported", field: "repositories", detail: `invalid repository access '${access}' on ${repoId}` };
}
}
const hasWrite = Object.values(repositories).some((access) => access === "write");
if (!hasWrite) {
return { reason: "step_unsupported", field: "repositories", detail: "command gates require at least one repository with write access" };
}
}
const expectPass = step.expect === "pass";
if (expectPass) {
if (!step.outcomes.includes("passed")) {
return { reason: "gate_outcome_undeclared", field: "outcomes", detail: "step expects pass but missing required outcome passed; spell it as 'passed'" };
}
if (!step.outcomes.includes("implementation-failure") && !step.outcomes.includes("failed")) {
return { reason: "gate_outcome_undeclared", field: "outcomes", detail: "step expects pass but missing required failure outcome; declare implementation-failure or failed" };
}
} else {
if (!step.outcomes.includes("repro-missing")) {
return { reason: "gate_outcome_undeclared", field: "outcomes", detail: "step expects fail but missing required outcome repro-missing; spell it as 'repro-missing'" };
}
if (!step.outcomes.includes("implementation-failure") && !step.outcomes.includes("failed")) {
return { reason: "gate_outcome_undeclared", field: "outcomes", detail: "step expects fail but missing required failure outcome; declare implementation-failure or failed" };
}
}
if (context && projectRuntimeKey(context.projectRoot) !== envelope2.gates.controlRoot.projectKey) {
throw runtimeError("run_owner_mismatch", plan.workflowId, `gate control root does not match project`);
}
if (definition.kind === "artifacts-exist" && step.expect === "fail") {
return { reason: "step_unsupported", field: "expect", detail: "artifacts-exist gates cannot expect fail" };
}
return void 0;
}
function pinnedGatesForCompiledPlan(plan, bundle, projectRoot) {
const referenced = /* @__PURE__ */ new Set();
for (const step of Object.values(plan.steps)) {
if (step.kind === "gate") referenced.add(step.gate);
}
const definitions = /* @__PURE__ */ Object.create(null);
const registryValue = bundle.gateRegistry?.value;
const gatesObject = registryValue && typeof registryValue.gates === "object" && registryValue.gates && !Array.isArray(registryValue.gates) ? registryValue.gates : {};
for (const gateId of referenced) {
definitions[gateId] = parseGateDefinition(gatesObject[gateId], gateId, plan.workflowId);
}
return {
registry: referenced.size > 0 && bundle.gateRegistry ? { schema: "kxm.gate-registry.v1", hash: gateRegistryHash(bundle.gateRegistry.value) } : bundle.gateRegistry && referenced.size === 0 ? { schema: "kxm.gate-registry.v1", hash: gateRegistryHash(bundle.gateRegistry.value) } : null,
definitions,
controlRoot: { repositoryId: "control", projectKey: projectRuntimeKey(projectRoot) }
};
}
function gateRecoveryPreflight(context) {
const attempts = context.eventStore.gateAttemptsForProject(context.projectId);
const capabilities = context.eventStore.issuedOrRevokedCapabilities();
const seenAttempts = /* @__PURE__ */ new Set();
const blocking = [];
let owned = 0;
for (const row of attempts) {
seenAttempts.add(row.attemptId);
const classified = classifyRecoverableGateAttempt(context, row, context.eventStore.capabilityByAttempt(row.attemptId));
if (classified === "owned") owned += 1;
else if (classified === "blocking") blocking.push({ runId: row.runId, attemptId: row.attemptId });
}
for (const capability of capabilities) {
if (seenAttempts.has(capability.attemptId)) continue;
const row = context.eventStore.gateAttempt(capability.attemptId);
if (capability.producerId === "driver-simulated" || capability.producerId === "pi" || capability.producerId === "oneshot") {
if (row) {
throw runtimeError(
"gate_recovery_corrupt",
capability.attemptId,
"gate recovery preflight: capability producer contradicts gate attempt"
);
}
continue;
}
if (capability.producerId !== "kxm-gate") {
throw runtimeError(
"gate_recovery_corrupt",
capability.attemptId,
`gate recovery preflight: unknown capability producer ${capability.producerId}`
);
}
if (!row) {
throw runtimeError("gate_recovery_corrupt", capability.attemptId, "gate recovery preflight: missing gate_attempts row");
}
const classified = classifyRecoverableGateAttempt(context, row, capability);
if (classified === "owned") owned += 1;
else if (classified === "blocking") blocking.push({ runId: row.runId, attemptId: row.attemptId });
}
return { owned, blocking };
}
function classifyRecoverableGateAttempt(context, row, capability) {
if (row.producerId !== "kxm-gate") {
throw runtimeError(
"gate_recovery_corrupt",
row.attemptId,
"gate recovery preflight: capability producer contradicts gate attempt"
);
}
if (capability && capability.producerId !== "kxm-gate") {
throw runtimeError(
"gate_recovery_corrupt",
row.attemptId,
"gate recovery preflight: capability producer contradicts gate attempt"
);
}
if (capability && (row.runId !== capability.runId || row.assignmentId !== capability.assignmentId || row.stepId !== capability.stepId || row.stepAttempt !== capability.stepAttempt || row.attemptId !== capability.attemptId)) {
throw runtimeError("gate_recovery_corrupt", capability.attemptId, "gate recovery preflight: capability identity does not match gate attempt");
}
const run = context.eventStore.run(row.runId);
if (!run) {
throw runtimeError("gate_recovery_corrupt", row.runId, "gate recovery preflight: run does not exist");
}
if (run.projectId !== context.projectId || row.projectId !== context.projectId) {
throw runtimeError("gate_recovery_corrupt", row.runId, "gate recovery preflight: run project mismatch");
}
let state;
try {
state = foldStoredKxmRun(context, run);
} catch (error) {
throw runtimeError(
"gate_recovery_corrupt",
row.runId,
`gate recovery preflight: fold error: ${error instanceof Error ? error.message : String(error)}`
);
}
const observation = context.eventStore.gateObservationForAttempt(row.attemptId);
const evidence = context.eventStore.gateEvidenceForAttempt(row.attemptId);
const events = context.eventStore.events(row.runId, 0, 1e6);
if (isExcludedTerminalProof(state, row, observation, evidence, events)) return "excluded";
if (isEvaluatedSettledProof(row, observation, evidence)) {
if (capability && (capability.state === "issued" || capability.state === "revoked") && state.currentStep?.attemptId === row.attemptId && state.currentStep.effectState === "settled") {
throw runtimeError(
"gate_recovery_corrupt",
row.runId,
"gate recovery preflight: capability remains issued or revoked after evaluated settlement"
);
}
return "excluded";
}
if (!capability || capability.producerId !== "kxm-gate" || capability.state !== "issued" && capability.state !== "revoked") {
throw runtimeError(
"gate_recovery_corrupt",
row.attemptId,
"gate recovery preflight: unfinished gate attempt is missing issued or revoked kxm-gate capability"
);
}
const current = state.currentStep;
const sameAttempt = current?.attemptId === row.attemptId && current.assignmentId === row.assignmentId && current.effectId === row.effectId && current.stepId === row.stepId;
const controller = kxmAttemptController(context.eventStore.path, row.runId, row.attemptId);
if (row.gateKind === "command") {
const hold = kxmGateHold(context.eventStore.path, row.runId);
const admittedToken = kxmAdmittedToken(context.eventStore.path, row.runId);
if (hold && hold.attemptId !== row.attemptId) {
throw runtimeError("gate_recovery_corrupt", row.attemptId, "gate recovery preflight: gate hold does not match the attempt");
}
if (hold && admittedToken !== void 0 && hold.token !== admittedToken) {
throw runtimeError("gate_recovery_corrupt", row.attemptId, "gate recovery preflight: gate hold token does not match admission");
}
if (hold?.state === "unsettled") return "blocking";
const ownedCommand = run.homeRuntimeId === context.homeRuntimeId && sameAttempt && hold?.state === "active" && hold.attemptId === row.attemptId && hold.token === admittedToken && controller?.attemptId === row.attemptId && current?.effectState !== "blocked_uncertain";
if (ownedCommand) return "owned";
return "blocking";
}
const ownedHere = run.homeRuntimeId === context.homeRuntimeId && sameAttempt && controller?.attemptId === row.attemptId && current?.effectState !== "blocked_uncertain";
if (ownedHere) return "owned";
return "blocking";
}
function gateRowIdentityMatches(row, other) {
return other.attemptId === row.attemptId && other.assignmentId === row.assignmentId && other.effectId === row.effectId && other.stepId === row.stepId && other.runId === row.runId;
}
function isEvaluatedSettledProof(row, observation, evidence) {
if (!evidence || !observation) return false;
if (!gateRowIdentityMatches(row, observation) || !gateRowIdentityMatches(row, evidence)) return false;
if (evidence.observationId !== observation.observationId) return false;
return observation.completeness === "complete";
}
function proofOnlySettledEvent(events, row) {
return events.find((event) => {
if (event.eventType !== "effect.settled" || event.runId !== row.runId) return false;
if (event.payload.attemptId !== row.attemptId || event.payload.assignmentId !== row.assignmentId || event.payload.effectId !== row.effectId || event.payload.stepId !== row.stepId) {
return false;
}
const refs = event.payload.evidenceRefs;
return !Array.isArray(refs) || refs.length === 0;
});
}
function isExcludedTerminalProof(state, row, observation, evidence, events) {
if (evidence) return false;
if (!observation) return false;
if (!gateRowIdentityMatches(row, observation)) return false;
if (observation.completeness === "incomplete") {
if (state.status === "failed" || state.status === "cancelled") return true;
const currentAttemptNumber = state.stepAttempts[row.stepId] ?? 0;
if (row.stepAttempt !== void 0 && currentAttemptNumber > row.stepAttempt) return true;
if (state.pendingStepId !== void 0 && (state.pendingStepId !== row.stepId || state.currentStep === void 0)) return true;
return false;
}
if (observation.completeness !== "no-start" && observation.completeness !== "complete") return false;
if (proofOnlySettledEvent(events, row)) {
return observation.completeness === "no-start" || observation.completeness === "complete";
}
const current = state.currentStep;
if (current) {
if (current.attemptId !== row.attemptId || current.assignmentId !== row.assignmentId || current.effectId !== row.effectId || current.stepId !== row.stepId || current.effectState !== "settled-proof") {
return false;
}
if (observation.completeness === "no-start" && current.observationCompleteness === "no-start") return true;
return observation.completeness === "complete" && current.observationCompleteness === "complete" && current.status === "cancelled";
}
if (observation.completeness === "no-start" && (state.status === "failed" || state.status === "cancelled")) return true;
return observation.completeness === "complete" && (state.status === "cancelled" || state.status === "failed");
}
function settlePreparedGate(context, prepared, observation) {
const run = requireRun(context, prepared.run.runId);
const folded = foldStoredKxmRun(context, run);
const current = folded.currentStep;
if (!current || current.stepId !== prepared.stepId || current.stepAttempt !== prepared.stepAttempt || current.assignmentId !== prepared.assignmentId || current.attemptId !== prepared.attemptId || current.effectId !== prepared.effectId) {
throw runtimeError("run_events_illegal", run.runId, "settlement identity does not match the prepared gate attempt");
}
const capability = context.eventStore.capabilityByAttempt(prepared.attemptId);
if (!capability || capability.runId !== run.runId || capability.attemptId !== prepared.attemptId || capability.assignmentId !== prepared.assignmentId || capability.stepId !== prepared.stepId || capability.stepAttempt !== prepared.stepAttempt || capability.producerId !== "kxm-gate" || capability.state !== "issued" && capability.state !== "revoked") {
throw runtimeError("run_events_illegal", run.runId, "prepared gate capability is not the issued or revoked attempt");
}
const cancelled = folded.status === "cancelling" || capability.state === "revoked";
if (observation.completeness !== "complete") {
throw runtimeError("gate_row_invalid", run.runId, "gate settlement requires a complete observation");
}
const settled = cancelled ? recordGateCancelObservedInTransaction(context, run, prepared.envelope, prepared.stepId, observation) : recordGateSettlementInTransaction(context, run, prepared.envelope, prepared.stepId, observation);
kxmGateDispatchSeams.afterObservationWrite?.(prepared);
return settled;
}
function requireRun(context, runId) {
const run = context.eventStore.run(runId);
if (!run) throw runtimeError("run_unknown", runId, "run does not exist in this event store");
if (run.projectId !== context.projectId || run.homeRuntimeId !== context.homeRuntimeId) {
throw runtimeError("run_owner_mismatch", runId, "run is not owned by this runtime context");
}
return run;
}
function recoverKxmRun(context, runId, request) {
return context.eventStore.transaction(() => {
const run = requireRun(context, runId);
let state = foldStoredKxmRun(context, run);
if (state.status !== "blocked_uncertain" && state.status !== "cancelling" && state.currentStep?.effectState !== "blocked_uncertain") {
throw runtimeError("run_events_illegal", runId, `run ${runId} is not in blocked_uncertain status`);
}
if (state.status === "cancelling" && state.currentStep?.effectState === "blocked_uncertain") {
state = { ...state, status: "blocked_uncertain" };
}
const now = (/* @__PURE__ */ new Date()).toISOString();
let sequence = context.eventStore.nextSequence(runId);
let mono = kxmMonotonicNs();
const events = [];
const push2 = (eventType, payload) => {
events.push({
...kxmEventBase(context, run, now, mono, request.commandId),
eventId: newKxmEventId(),
eventType,
sequence: sequence++,
payload
});
mono = kxmIncrementMonotonicNs(mono);
};
if (state.status === "running" && state.currentStep?.effectState === "blocked_uncertain") {
push2("run.status_changed", {
status: "blocked_uncertain",
previousStatus: "running",
reason: request.reason ?? "uncertain gate effect"
});
for (const ev of events) context.eventStore.appendEvent(ev);
events.length = 0;
state = foldStoredKxmRun(context, run);
context.eventStore.updateRunStatus(runId, "blocked_uncertain", now);
}
const attemptId = state.currentStep?.attemptId;
if (attemptId) {
resolveKxmGateHold(context.eventStore.path, runId, attemptId);
unregisterKxmAttemptController(context.eventStore.path, runId, attemptId);
const cap = context.eventStore.capabilityByAttempt(attemptId);
if (cap && cap.state !== "settled") {
context.eventStore.settleCapability(attemptId, "settled");
}
}
if (request.action === "retry" || request.action === "unblock") {
push2("run.status_changed", {
status: "running",
previousStatus: "blocked_uncertain",
reason: request.reason ?? "operator_retry"
});
for (const ev of events) context.eventStore.appendEvent(ev);
const nextState = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, nextState, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(runId, "running", now);
return { state: nextState, unblocked: true };
}
if (request.action === "fail") {
push2("run.status_changed", {
status: "failed",
previousStatus: "blocked_uncertain",
reason: request.reason ?? "operator_fail"
});
for (const ev of events) context.eventStore.appendEvent(ev);
const nextState = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, nextState, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(runId, "failed", now);
return { state: nextState, unblocked: true };
}
if (request.action === "cancel") {
push2("run.cancel_requested", {
actor: { kind: "runtime", id: context.homeRuntimeId },
reason: request.reason ?? "operator_cancel"
});
push2("run.status_changed", {
status: "cancelling",
previousStatus: "blocked_uncertain",
reason: request.reason ?? "operator_cancel"
});
push2("run.status_changed", {
status: "cancelled",
previousStatus: "cancelling",
reason: request.reason ?? "operator_cancel"
});
for (const ev of events) context.eventStore.appendEvent(ev);
const nextState = foldStoredKxmRun(context, run);
persistKxmRunState(context, runId, nextState, events[events.length - 1].sequence);
context.eventStore.updateRunStatus(runId, "cancelled", now);
return { state: nextState, unblocked: true };
}
throw runtimeError("run_events_illegal", runId, `unsupported recovery action ${request.action}`);
});
}
// plugins/kxm/src/oneshot-producer.ts
function isClosingFence(line) {
return /^(`{3,}|~{3,})\s*$/.test(line.trim());
}
function stripOneClosingFence(trimmed) {
const lineBreak = Math.max(trimmed.lastIndexOf("\n"), trimmed.lastIndexOf("\r"));
const lastLine = lineBreak < 0 ? trimmed : trimmed.slice(lineBreak + 1);
if (!isClosingFence(lastLine)) return trimmed;
if (lineBreak < 0) return "";
return trimmed.slice(0, lineBreak).trimEnd();
}
var MAX_OUTCOME_CLOSERS = 32;
var MAX_OUTCOME_OPENERS = 32;
var MAX_OUTCOME_SLICE_BYTES = 256 * 1024;
var MAX_OUTCOME_PARSE_BYTES = 1024 * 1024;
var MAX_PREFIX_CONTAINER_OPENERS = 16;
function outcomePrefixIsAnchored(prefix) {
let objectDepth = 0;
let arrayDepth = 0;
let inString = false;
let escape2 = false;
for (let i = 0; i < prefix.length; i++) {
const ch = prefix[i];
if (inString) {
if (escape2) {
escape2 = false;
continue;
}
if (ch === "\\") {
escape2 = true;
continue;
}
if (ch === '"') inString = false;
continue;
}
if (ch === '"') {
inString = true;
continue;
}
if (ch === "{") objectDepth += 1;
else if (ch === "}" && objectDepth > 0) objectDepth -= 1;
else if (ch === "[") arrayDepth += 1;
else if (ch === "]" && arrayDepth > 0) arrayDepth -= 1;
}
return objectDepth === 0 && arrayDepth === 0 && !inString && !escape2;
}
function containerLexIsTruncated(body, start) {
const stack = [];
let inString = false;
let escape2 = false;
for (let i = start; i < body.length; i++) {
const ch = body[i];
if (inString) {
if (escape2) {
escape2 = false;
continue;
}
if (ch === "\\") {
escape2 = true;
continue;
}
if (ch === '"') inString = false;
continue;
}
if (ch === '"') {
inString = true;
continue;
}
if (ch === "{" || ch === "[") {
stack.push(ch);
continue;
}
if (ch === "}" || ch === "]") {
const open2 = ch === "}" ? "{" : "[";
const top = stack[stack.length - 1];
if (top !== open2) return false;
stack.pop();
}
}
return stack.length > 0 || inString || escape2;
}
function prefixHidesTruncatedContainer(body, openAt) {
let seen = 0;
for (let i = openAt - 1; i >= 0; i--) {
const ch = body[i];
if (ch !== "{" && ch !== "[") continue;
if (seen >= MAX_PREFIX_CONTAINER_OPENERS) return true;
seen++;
if (containerLexIsTruncated(body, i)) return true;
}
return false;
}
function determineOutcome(text, allowedOutcomes) {
const trimmed = text.trim();
if (!trimmed) return "failed";
const body = stripOneClosingFence(trimmed);
if (!body) return "failed";
let seenClosers = 0;
let parseBytes = 0;
for (let closeAt = body.length - 1; closeAt >= 0 && seenClosers < MAX_OUTCOME_CLOSERS; closeAt--) {
if (body[closeAt] !== "}") continue;
seenClosers++;
const end = closeAt + 1;
if (end !== body.length) continue;
let seenOpeners = 0;
for (let openAt = closeAt - 1; openAt >= 0 && seenOpeners < MAX_OUTCOME_OPENERS; openAt--) {
if (body[openAt] !== "{") continue;
seenOpeners++;
const slice = body.slice(openAt, end);
const sliceBytes = Buffer.byteLength(slice, "utf8");
if (sliceBytes > MAX_OUTCOME_SLICE_BYTES) break;
if (parseBytes + sliceBytes > MAX_OUTCOME_PARSE_BYTES) return "failed";
parseBytes += sliceBytes;
let result;
try {
result = JSON.parse(slice);
} catch {
continue;
}
if (!result || typeof result !== "object" || Array.isArray(result)) continue;
const outcome = result.outcome;
if (typeof outcome !== "string" || !allowedOutcomes.includes(outcome)) continue;
const prefix = body.slice(0, openAt).trimEnd();
if (!outcomePrefixIsAnchored(prefix)) continue;
if (prefixHidesTruncatedContainer(body, openAt)) continue;
return outcome;
}
}
return "failed";
}
function createKxmOneShotProducer(options = {}) {
const running = /* @__PURE__ */ new Map();
let closed = false;
function requireHarness(request) {
if (request.harness) return request.harness;
throw new Error("producer_harness_required");
}
function parseModelString(spec, harness) {
const trimmed = spec.trim();
if (trimmed.includes("/")) {
const idx = trimmed.indexOf("/");
return { provider: trimmed.slice(0, idx).toLowerCase(), model: trimmed.slice(idx + 1) };
}
const fallbackProvider = NATIVE_HARNESS_PROVIDERS[harness] ?? options.defaultProvider ?? "anthropic";
return { provider: fallbackProvider, model: trimmed };
}
function resolveModelForRequest(request, harness) {
if (request.model) {
if (request.provider) {
return { provider: request.provider.toLowerCase(), model: request.model, thinking: request.thinking };
}
const parsed = parseModelString(request.model, harness);
return {
provider: request.provider?.toLowerCase() ?? parsed.provider,
model: parsed.model,
thinking: request.thinking
};
}
if (options.resolveModel) {
const resolved = options.resolveModel(request.agentId, request.runId);
if (resolved && resolved.model) {
if (resolved.provider) {
return { provider: resolved.provider.toLowerCase(), model: resolved.model, thinking: resolved.thinking };
}
const parsed = parseModelString(resolved.model, harness);
return {
provider: resolved.provider?.toLowerCase() ?? parsed.provider,
model: parsed.model,
thinking: resolved.thinking
};
}
}
if (options.defaultModel) {
const parsed = parseModelString(options.defaultModel, harness);
return { provider: parsed.provider, model: parsed.model, thinking: request.thinking };
}
throw new Error("producer_route_not_admitted");
}
async function checkAuth(harness, provider, model, env, signal) {
if (options.inventory) {
const entry = options.inventory.harnesses.find((h) => h.id === harness);
if (!entry || !entry.detected || entry.authenticated !== true) {
throw new Error(`${harness}_not_authenticated: ${harness} harness not authenticated in inventory`);
}
}
const probeFn = options.probeHarness ?? probeHarnessAssignmentAsync;
const probe = await probeFn({ harness, provider, model, env, signal, timeoutMs: 1e4 });
if (!probe.detected) {
throw new Error(`${harness}_not_authenticated: ${harness} harness not detected (${probe.issues.join(", ")})`);
}
if (probe.authenticated !== true) {
throw new Error(`${harness}_not_authenticated: ${harness} not authenticated (${probe.issues.join(", ")})`);
}
return probe;
}
async function executeRequest(request) {
const startTime = Date.now();
const harness = requireHarness(request);
const resolved = resolveModelForRequest(request, harness);
if (closed) throw new Error("oneshot_producer_closed");
const cancelled = () => ({
outcome: "cancelled",
costBasis: "unknown",
costUsd: null,
latencyMs: Math.max(0, Date.now() - startTime),
harness,
provider: resolved.provider,
requestedModel: resolved.model,
effectiveModel: "unknown",
agentRole: request.agentRole ?? request.agentId
});
if (request.signal.aborted) return cancelled();
const catalogEntry = (options.catalog ?? BUILTIN_HARNESSES).find((h) => h.id === harness);
if (!catalogEntry?.oneShot) throw new Error(`oneshot_harness_unsupported: ${harness}`);
const permission = request.permission === "edit" || request.contextPacket?.task.permissionCeiling === "edit" ? "edit" : "read-only";
const permissionArgs = oneShotPermissionArgs(harness, permission);
if (!permissionArgs) {
throw new Error(`oneshot_harness_unsupported: ${harness} ${permission === "edit" ? "writer_profile_unaudited" : "permission_profile_unaudited"}`);
}
const env = { ...options.env ?? process.env };
let auth;
try {
auth = await checkAuth(harness, resolved.provider, resolved.model, env, request.signal);
} catch (error) {
if (request.signal.aborted) return cancelled();
throw error;
}
if (request.signal.aborted) return cancelled();
const command = auth.command ?? catalogEntry.commands[0] ?? harness;
const oneShot = catalogEntry.oneShot;
let args;
if (harness === "claude") {
args = [
"-p",
"--model",
resolved.model,
...resolved.thinking ? ["--effort", resolved.thinking] : [],
...permissionArgs,
"--output-format",
"json"
];
} else if (harness === "codex") {
args = [
"exec",
"-m",
resolved.model,
...resolved.thinking ? ["-c", `model_reasoning_effort="${resolved.thinking}"`] : [],
...permissionArgs,
"--json",
"-"
];
} else if (harness === "grok") {
args = [
"--model",
resolved.model,
...resolved.thinking ? ["--reasoning-effort", resolved.thinking] : [],
...permissionArgs,
"--output-format",
"json"
];
} else if (harness === "agy") {
args = [
"-m",
resolved.model,
...permissionArgs,
"--output-format",
"json",
"-p"
];
} else if (harness === "kimi") {
args = [
"-m",
resolved.model,
...permissionArgs,
"--output-format",
"stream-json",
"-p"
];
} else if (harness === "pi") {
const qualified = resolved.provider && resolved.model.startsWith(`${resolved.provider}/`) ? resolved.model : resolved.provider ? `${resolved.provider}/${resolved.model}` : resolved.model;
args = [
"--model",
qualified,
...permissionArgs,
...oneShot.argv
];
} else {
throw new Error(`oneshot_harness_unsupported: ${harness} permission_profile_unaudited`);
}
const taskPrompt = request.prompt ?? `Execute step ${request.stepId} (attempt ${request.stepAttempt}) for agent ${request.agentId}.`;
const promptMessage = `${taskPrompt}
Return a final JSON object with an "outcome" field chosen from ${JSON.stringify(request.allowedOutcomes)} and a concise "summary". Do not wrap it in Markdown. If no allowed outcome is truthful, return {"outcome":"failed"}; never infer success from an incomplete task.`;
let input;
if (oneShot.promptVia === "stdin") {
input = promptMessage;
} else {
if (harness === "grok") args.push("--single");
args.push(promptMessage);
}
const spawnFn = options.spawnProcess ?? defaultSpawn;
const cwd = options.projectRoot ?? process.cwd();
const timeoutMs = request.timeoutMs ?? options.timeoutMs;
const evidence = await beginOneShotEvidence(options.evidenceRoot ?? oneShotEvidenceRoot(), {
runId: request.runId,
stepId: request.stepId,
attemptId: request.attemptId,
assignmentId: request.assignmentId,
harness,
provider: resolved.provider,
model: resolved.model,
cwd,
command,
args,
input,
timeoutMs: timeoutMs ?? 12e4
}, [request.capability, ...Object.entries(env).filter(([key]) => /TOKEN|KEY|SECRET|PASSWORD|COOKIE|AUTH/i.test(key)).map(([, value]) => value ?? "")]);
let procResult;
try {
procResult = request.signal.aborted ? { stdout: "", stderr: "", code: null, started: false, observedChildExit: false, error: new Error("process_aborted") } : await spawnFn(command, args, { cwd, env, input, timeoutMs, signal: request.signal });
} catch (error) {
procResult = { stdout: "", stderr: "", code: null, observedChildExit: false, error: error instanceof Error ? error : new Error("process_adapter_error") };
}
let parsed;
try {
parsed = oneShot.usageParser(procResult.stdout, procResult.stderr, resolved.model);
} catch {
parsed = { text: "", isError: true };
}
const aborted = request.signal.aborted || procResult.error?.message === "process_aborted";
const unverifiedDescendants = procResult.unverifiedDescendants === true || procResult.terminationRequested === true || procResult.error?.message === "process_exit_unobserved" || procResult.observedChildExit === false && procResult.started !== false;
const effectUncertain = unverifiedDescendants || Boolean(procResult.signal);
const transportFailed = procResult.code !== 0 || Boolean(procResult.error) || effectUncertain;
const outcome = aborted ? "cancelled" : transportFailed || parsed.isError ? "failed" : determineOutcome(parsed.text, request.allowedOutcomes);
const providerMetadata = {
processStatus: aborted ? "aborted" : transportFailed ? "failed" : "completed",
executionEvidenceId: evidence.id,
permission,
permissionProfile: permission === "edit" ? "writer" : "read-only",
authored: false
};
if (procResult.code !== null && Number.isFinite(procResult.code)) providerMetadata.processExitCode = procResult.code;
if (procResult.signal) providerMetadata.processSignal = procResult.signal;
if (procResult.observedChildExit !== void 0) providerMetadata.observedChildExit = procResult.observedChildExit;
if (procResult.started !== void 0) providerMetadata.processStarted = procResult.started;
if (procResult.terminationRequested !== void 0) providerMetadata.terminationRequested = procResult.terminationRequested;
if (unverifiedDescendants) providerMetadata.descendantEffects = "unverified";
if (procResult.error) {
const reason = procResult.error.message;
providerMetadata.processError = /^process_(aborted|timeout|output_limit|stdin_error|stdio_error|stdio_unclosed|exit_unobserved)$/.test(reason) ? reason : "process_error";
}
const latencyMs = Math.max(0, Date.now() - startTime);
const usage = parsed.usage;
const validCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
const boundedCount = (field, value) => {
if (validCount(value) && value <= 1e6) return value;
if (typeof value === "number" && Number.isFinite(value)) {
providerMetadata[`raw${field[0].toUpperCase()}${field.slice(1)}`] = value;
}
return null;
};
const tokensIn = boundedCount("tokensIn", usage?.tokensIn);
const tokensOut = boundedCount("tokensOut", usage?.tokensOut);
const cacheReadTokens = boundedCount("cacheReadTokens", usage?.cacheReadTokens);
const cacheWriteTokens = boundedCount("cacheWriteTokens", usage?.cacheWriteTokens);
const contextTokens = boundedCount("contextTokens", usage?.contextTokens);
if (typeof usage?.costUsd === "number" && Number.isFinite(usage.costUsd) && usage.costUsd >= 0) providerMetadata.providerReportedCostUsd = usage.costUsd;
let catalog;
try {
catalog = options.priceCatalog ? parsePriceCatalog(JSON.stringify(options.priceCatalog)) : loadPriceCatalog(options.projectRoot ?? process.cwd());
} catch {
providerMetadata.priceCatalogUnavailable = true;
}
if (catalog && catalog.date !== (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
providerMetadata.priceCatalogStale = true;
catalog = void 0;
}
const subscription = ["claude.ai", "ChatGPT", "antigravity-oauth"].includes(auth.authMethod ?? "");
const costBasis = subscription ? "unmetered" : "unknown";
const costUsd = null;
const priceRef = subscription ? `subscription:${harness}` : void 0;
if (auth.authMethod) providerMetadata.authMethod = auth.authMethod;
const priceRow = catalog ? findModelPrice(catalog, resolved.model, resolved.provider) : void 0;
const flatTier = priceRow?.tiers.length === 1 && priceRow.tiers[0]?.upToContextTokens == null ? priceRow.tiers[0] : void 0;
if (catalog && harness === "claude" && flatTier && validCount(usage?.tokensIn) && validCount(usage?.tokensOut) && validCount(usage?.cacheReadTokens) && validCount(usage?.cacheWriteTokens) && (usage.cacheReadTokens === 0 || flatTier.cacheReadPerMillion != null) && (usage.cacheWriteTokens === 0 || flatTier.cacheWritePerMillion != null)) {
const calculated = calculateModelCost(catalog, {
model: resolved.model,
provider: resolved.provider,
tokensIn: usage.tokensIn,
tokensOut: usage.tokensOut,
cacheReadTokens: usage.cacheReadTokens,
cacheWriteTokens: usage.cacheWriteTokens,
contextTokens
});
if (calculated && Number.isFinite(calculated.costUsd)) {
providerMetadata.listCostUsd = calculated.costUsd;
providerMetadata.listPriceRef = calculated.priceRef;
providerMetadata.listPriceSha256 = catalog.sha256;
}
}
const result = {
outcome,
costBasis,
costUsd,
tokensIn,
tokensOut,
cacheReadTokens,
cacheWriteTokens,
contextTokens,
latencyMs,
harness,
provider: resolved.provider,
requestedModel: resolved.model,
effectiveModel: parsed.effectiveModel ?? "unknown",
providerMetadata,
...effectUncertain ? { effectUncertain: true } : {},
...resolved.thinking !== void 0 ? { thinking: resolved.thinking } : {},
agentRole: request.agentRole ?? request.agentId,
...priceRef !== void 0 ? { priceRef } : {}
};
try {
providerMetadata.executionEvidenceSha256 = await evidence.finish(procResult, result);
} catch {
providerMetadata.evidenceWriteFailed = true;
return { ...result, outcome: "failed", effectUncertain: true };
}
return result;
}
const producer = {
id: "oneshot",
produce(request) {
const controller = new AbortController();
const signal = AbortSignal.any([request.signal, controller.signal]);
const pending = Promise.resolve().then(() => executeRequest({ ...request, signal })).finally(() => {
running.delete(controller);
});
running.set(controller, pending);
return pending;
},
async close() {
closed = true;
const pending = [...running.values()];
for (const controller of running.keys()) controller.abort();
await Promise.allSettled(pending);
}
};
registerTrustedProducer(producer);
return producer;
}
// plugins/kxm/src/client.ts
import { hostname } from "node:os";
function defaultHostLabel() {
try {
return hostname().trim().slice(0, MAX_AGENT_HOST_CHARS) || void 0;
} catch {
return void 0;
}
}
var HubHttpError = class extends Error {
statusCode;
code;
requestId;
extras;
constructor(statusCode, message, code, requestId, extras) {
super(message);
this.name = "HubHttpError";
this.statusCode = statusCode;
if (code) this.code = code;
if (requestId) this.requestId = requestId;
if (extras) this.extras = extras;
}
};
async function hubJsonRequest(options, path, init, headers) {
const requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
const timeoutSignal = AbortSignal.timeout(requestTimeoutMs);
const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
let response;
try {
response = await (options.fetchImpl ?? fetch)(`${options.serverUrl.replace(/\/$/, "")}${path}`, {
...init,
signal,
headers: { ...headers, ...init.headers ?? {} }
});
} catch (error) {
if (timeoutSignal.aborted) throw new Error(`request timed out after ${requestTimeoutMs}ms`);
throw error;
}
const text = await response.text();
let body = {};
if (text) {
try {
body = JSON.parse(text);
} catch {
throw new Error(`hub returned invalid JSON with HTTP ${response.status}`);
}
}
if (!response.ok) {
const extras = {};
for (const key of ["operation", "nextAction", "assignedCoordinatorName"]) {
if (typeof body[key] === "string") extras[key] = body[key];
}
if (body.lease && typeof body.lease === "object") extras.lease = body.lease;
throw new HubHttpError(
response.status,
String(body.error ?? `HTTP ${response.status}`),
typeof body.code === "string" ? body.code : void 0,
response.headers.get("x-request-id") ?? void 0,
Object.keys(extras).length > 0 ? extras : void 0
);
}
return body;
}
var RuntimeHubClient = class {
options;
constructor(options) {
this.options = options;
}
async heartbeat() {
const result = await this.request("/v1/runtime/presence", {
project: this.options.project,
runtimeId: this.options.runtimeId,
host: this.options.host ?? defaultHostLabel()
});
return result.presence;
}
/** Push already-derived `kxm.sync-event.v1` objects, in outbox order. */
async pushSyncEvents(events) {
return await this.request("/v1/sync/events", {
project: this.options.project,
runtimeId: this.options.runtimeId,
events
});
}
async request(path, body) {
const headers = { "content-type": "application/json" };
if (this.options.authToken) headers.authorization = `Bearer ${this.options.authToken}`;
return await hubJsonRequest(this.options, path, { method: "POST", body: JSON.stringify(body) }, headers);
}
};
// plugins/kxm/src/hub-binding.ts
import { spawnSync as spawnSync6 } from "node:child_process";
import { existsSync as existsSync16, mkdirSync as mkdirSync7, readFileSync as readFileSync14, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "node:fs";
import { homedir as homedir3 } from "node:os";
import { dirname as dirname9, isAbsolute as isAbsolute6, join as join19, resolve as resolve10 } from "node:path";
var HUB_BINDING_SCHEMA = "kxm.hub-binding.v1";
var CloudTokenError = class extends Error {
code;
constructor(code, message) {
super(message);
this.name = "CloudTokenError";
this.code = code;
}
};
var TOKEN_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
var TOKEN_COMMAND_TIMEOUT_MS = 15e3;
var TOKEN_COMMAND_MAX_BUFFER = 4096;
var HubBindingError = class extends Error {
constructor(message) {
super(message);
this.name = "HubBindingError";
}
};
function resolveUserStateRoot(env) {
const explicit = env.KXM_STATE_HOME?.trim();
if (explicit) {
if (!isAbsolute6(explicit)) throw new HubBindingError("local_state_root_not_absolute");
return resolve10(explicit);
}
if (process.platform === "win32") {
const localAppData = env.LOCALAPPDATA?.trim();
const base2 = localAppData && isAbsolute6(localAppData) ? localAppData : join19(homedir3(), "AppData", "Local");
return resolve10(base2, "KXM");
}
if (process.platform === "darwin") return resolve10(homedir3(), "Library", "Application Support", "KXM");
const xdgState = env.XDG_STATE_HOME?.trim();
const base = xdgState && isAbsolute6(xdgState) ? xdgState : join19(homedir3(), ".local", "state");
return resolve10(base, "kxm");
}
function hubBindingFile(env = process.env) {
return join19(resolveUserStateRoot(env), "hub-binding.json");
}
function hubBindingCloudFile(env = process.env) {
return join19(resolveUserStateRoot(env), "hub-binding.cloud.json");
}
function validateHubUrl(raw) {
let parsed;
try {
parsed = new URL(raw);
} catch {
throw new HubBindingError("hub_url_invalid");
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.username !== "" || parsed.password !== "" || parsed.search !== "" || parsed.hash !== "" || raw.includes("?") || raw.includes("#")) {
throw new HubBindingError("hub_url_invalid");
}
return parsed.href.replace(/\/$/, "");
}
function splitTokenCommand(raw) {
if (/[|&;<>$`\n\r]/.test(raw)) {
throw new CloudTokenError(
"cloud_token_command_invalid",
"token command must be a program and arguments, not a shell pipeline"
);
}
const args = [];
let current = "";
let quote;
for (const ch of raw) {
if (quote) {
if (ch === quote) quote = void 0;
else current += ch;
continue;
}
if (ch === "'" || ch === '"') {
quote = ch;
continue;
}
if (ch === " " || ch === " ") {
if (current.length > 0) {
args.push(current);
current = "";
}
continue;
}
current += ch;
}
if (quote) {
throw new CloudTokenError("cloud_token_command_invalid", "token command has an unclosed quote");
}
if (current.length > 0) args.push(current);
if (args.length === 0) {
throw new CloudTokenError("cloud_token_command_invalid", "token command is empty");
}
return args;
}
function isCloudTokenEnvName(value) {
return TOKEN_ENV_NAME.test(value);
}
function resolveCloudHubToken(binding, env = process.env) {
if (!binding.cloud) {
throw new CloudTokenError("cloud_token_missing", "cloud hub token is missing; the local hub-env token was not used");
}
if (binding.tokenEnv) {
const value = env[binding.tokenEnv]?.trim();
if (value) return value;
}
if (binding.tokenCommand) return runTokenCommand(binding.tokenCommand, env);
const source = binding.tokenEnv ? `${binding.tokenEnv} is unset or empty` : "no token source is configured";
throw new CloudTokenError(
"cloud_token_missing",
`cloud hub token is missing: ${source}; the local hub-env token was not used`
);
}
function runTokenCommand(command, env) {
const argv = splitTokenCommand(command);
const [program, ...args] = argv;
const result = spawnSync6(program, args, {
encoding: "utf8",
shell: false,
timeout: TOKEN_COMMAND_TIMEOUT_MS,
maxBuffer: TOKEN_COMMAND_MAX_BUFFER,
env,
windowsHide: true
});
if (result.error || result.status !== 0) {
throw new CloudTokenError(
"cloud_token_command_failed",
"token command failed; the local hub-env token was not used"
);
}
const stdout = result.stdout ?? "";
if (stdout.trim().length === 0 || stdout.trim() !== stdout.trim().split(/\r?\n/)[0]) {
throw new CloudTokenError(
"cloud_token_command_failed",
"token command did not print a single token; the local hub-env token was not used"
);
}
return stdout.trim();
}
function hubBindingScope(url) {
let host;
try {
host = new URL(url).hostname.toLowerCase();
} catch {
return "remote";
}
if (host === "localhost" || host === "::1" || host === "[::1]" || host.endsWith(".localhost")) return "loopback";
const v4 = /^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.exec(host);
return v4 && [v4[1], v4[2], v4[3]].every((part) => Number(part) <= 255) ? "loopback" : "remote";
}
function isIsoTimestamp(value) {
if (Number.isNaN(Date.parse(value))) return false;
return value === new Date(value).toISOString();
}
var LEGACY_BINDING_KEYS = ["schema", "url", "boundAt"];
var BINDING_KEYS = /* @__PURE__ */ new Set([...LEGACY_BINDING_KEYS, "cloud", "tokenEnv", "tokenCommand"]);
function bindingFallbackWarning(file, reason) {
return `hub binding at ${file} ${reason}; falling back to the local hub. Restart the Runtime supervisor, the hub, and workers after upgrading and before a cloud bind.`;
}
function writeBindingJson(file, value) {
mkdirSync7(dirname9(file), { recursive: true, mode: 448 });
const temporary = join19(dirname9(file), `.${file.endsWith("cloud.json") ? "hub-binding-cloud" : "hub-binding"}-${process.pid}.tmp`);
try {
writeFileSync8(temporary, `${JSON.stringify(value, null, 2)}
`, { encoding: "utf8", mode: 384 });
renameSync2(temporary, file);
} finally {
rmSync2(temporary, { force: true });
}
}
function parseBindingObject(file) {
if (!existsSync16(file)) return new HubBindingError(`missing hub binding at ${file}`);
let parsed;
try {
parsed = JSON.parse(readFileSync14(file, "utf8"));
} catch {
return new HubBindingError(`malformed hub binding at ${file}`);
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
return new HubBindingError(`malformed hub binding at ${file}`);
}
return parsed;
}
function cloudRecordFromRow(file, row, url, boundAt) {
if (row.cloud !== true) return void 0;
let tokenEnv;
let tokenCommand;
if (row.tokenEnv !== void 0) {
if (typeof row.tokenEnv !== "string" || !isCloudTokenEnvName(row.tokenEnv)) {
throw new HubBindingError(`malformed hub binding at ${file}`);
}
tokenEnv = row.tokenEnv;
}
if (row.tokenCommand !== void 0) {
if (typeof row.tokenCommand !== "string") throw new HubBindingError(`malformed hub binding at ${file}`);
try {
splitTokenCommand(row.tokenCommand);
} catch {
throw new HubBindingError(`malformed hub binding at ${file}`);
}
tokenCommand = row.tokenCommand;
}
if (!tokenEnv && !tokenCommand) throw new HubBindingError(`malformed hub binding at ${file}`);
return {
schema: HUB_BINDING_SCHEMA,
url,
boundAt,
cloud: true,
...tokenEnv ? { tokenEnv } : {},
...tokenCommand ? { tokenCommand } : {}
};
}
function interpretBindingFile(file) {
if (!existsSync16(file)) return {};
const parsed = parseBindingObject(file);
if (parsed instanceof HubBindingError) throw parsed;
const keys = Object.keys(parsed);
const unknown = keys.filter((key) => !BINDING_KEYS.has(key));
if (parsed.schema !== HUB_BINDING_SCHEMA || unknown.length > 0) {
return { warning: bindingFallbackWarning(file, `is newer than this build understands (${String(parsed.schema)})`) };
}
if (typeof parsed.url !== "string" || typeof parsed.boundAt !== "string" || !isIsoTimestamp(parsed.boundAt)) {
throw new HubBindingError(`malformed hub binding at ${file}`);
}
let url;
try {
url = validateHubUrl(parsed.url);
} catch {
throw new HubBindingError(`malformed hub binding at ${file}`);
}
const cloudish = keys.some((key) => key === "cloud" || key === "tokenEnv" || key === "tokenCommand");
if (!cloudish) {
if (keys.length !== 3) throw new HubBindingError(`malformed hub binding at ${file}`);
return { record: { schema: HUB_BINDING_SCHEMA, url, boundAt: parsed.boundAt } };
}
const record2 = cloudRecordFromRow(file, parsed, url, parsed.boundAt);
if (!record2) throw new HubBindingError(`malformed hub binding at ${file}`);
return { record: record2, legacyCloud: true };
}
function loadHubBinding(env = process.env) {
const cloudFile = hubBindingCloudFile(env);
const cloud = interpretBindingFile(cloudFile);
if (cloud.warning && !cloud.record) {
const local = existsSync16(hubBindingFile(env)) ? interpretBindingFile(hubBindingFile(env)) : {};
if (local.record && !local.record.cloud) return { record: local.record, warning: cloud.warning };
return { warning: cloud.warning };
}
if (cloud.record?.cloud) return { record: cloud.record, ...cloud.warning ? { warning: cloud.warning } : {} };
const main = interpretBindingFile(hubBindingFile(env));
if (main.legacyCloud && main.record) {
writeBindingJson(cloudFile, main.record);
rmSync2(hubBindingFile(env), { force: true });
return {
record: main.record,
warning: bindingFallbackWarning(
hubBindingFile(env),
"stored a cloud bind in the pre-0.7.160 file"
)
};
}
return { ...main.record ? { record: main.record } : {}, ...main.warning ? { warning: main.warning } : {} };
}
function readHubBinding(env = process.env) {
return loadHubBinding(env).record;
}
// plugins/kxm/src/hub-env.ts
import { existsSync as existsSync18, mkdirSync as mkdirSync8, readFileSync as readFileSync16, renameSync as renameSync3, rmSync as rmSync3, writeFileSync as writeFileSync9 } from "node:fs";
import { homedir as homedir4 } from "node:os";
import { dirname as dirname11, isAbsolute as isAbsolute7, join as join21, resolve as resolve12 } from "node:path";
// plugins/kxm/src/hub-identity.ts
var import_yaml12 = __toESM(require_dist(), 1);
import { spawnSync as spawnSync7 } from "node:child_process";
import { existsSync as existsSync17, readFileSync as readFileSync15 } from "node:fs";
import { basename as basename4, dirname as dirname10, join as join20, resolve as resolve11 } from "node:path";
var OP_TIMEOUT_MS = 15e3;
var OP_MAX_BUFFER = 4096;
function normalizeUrl(raw) {
try {
return validateHubUrl(raw);
} catch {
return void 0;
}
}
function projectYamlId(start) {
let dir = resolve11(start);
for (; ; ) {
const file = join20(dir, ".kxm", "project.yaml");
if (existsSync17(file)) {
try {
const doc = (0, import_yaml12.parse)(readFileSync15(file, "utf8"));
if (doc && typeof doc === "object" && !Array.isArray(doc) && typeof doc.id === "string" && doc.id.trim()) {
return doc.id.trim();
}
} catch {
}
return void 0;
}
const parent = dirname10(dir);
if (parent === dir) return void 0;
dir = parent;
}
}
function packageName(cwd) {
try {
const pkg = JSON.parse(readFileSync15(join20(cwd, "package.json"), "utf8"));
if (typeof pkg.name === "string" && pkg.name.trim().length > 0) return pkg.name.trim();
} catch {
}
return void 0;
}
function activeBinding(env) {
try {
return readHubBinding(env);
} catch (error) {
if (error instanceof HubBindingError) return void 0;
throw error;
}
}
function endpointFor(mode, settings) {
return mode === "cloud" ? settings.cloud : settings.local;
}
function resolveProjectIdentity(cwd, env = process.env, explicit) {
const fromExplicit = explicit?.trim();
if (fromExplicit) return { project: fromExplicit, source: "flag", sourceLabel: "--project" };
const fromEnv = env.KXM_PROJECT?.trim();
if (fromEnv) return { project: fromEnv, source: "env", sourceLabel: "KXM_PROJECT" };
const settings = loadHubSettings(cwd, env);
const mode = settings.mode ?? (activeBinding(env)?.cloud ? "cloud" : "local");
const fromConfig = endpointFor(mode, settings)?.project?.trim();
if (fromConfig) {
return { project: fromConfig, source: "config", sourceLabel: `.kxm/config.yaml hub.${mode}.project` };
}
const fromProject = projectYamlId(cwd);
if (fromProject) return { project: fromProject, source: "project.yaml", sourceLabel: ".kxm/project.yaml id" };
const fromPackage = packageName(cwd);
if (fromPackage) return { project: fromPackage, source: "package.json", sourceLabel: "package.json name" };
return { project: basename4(cwd), source: "directory", sourceLabel: "directory name" };
}
function defaultOpRead(reference, env) {
if (!isHubOpReference(reference)) {
throw new CloudTokenError("cloud_token_command_invalid", `refusing to resolve ${reference}; an op:// reference is required`);
}
const result = spawnSync7("op", ["read", reference], {
encoding: "utf8",
shell: false,
timeout: OP_TIMEOUT_MS,
maxBuffer: OP_MAX_BUFFER,
env,
windowsHide: true
});
if (result.error || result.status !== 0) {
throw new CloudTokenError(
"cloud_token_command_failed",
`op read failed for ${reference}; the token was not saved`
);
}
const line = (result.stdout ?? "").trim();
if (!line || line.split(/\r?\n/).length !== 1) {
throw new CloudTokenError(
"cloud_token_command_failed",
`op read did not print a single token for ${reference}; the token was not saved`
);
}
return line;
}
function resolveKeyReference(ref, env, opRead = defaultOpRead) {
if (!ref) return void 0;
if (ref.env) {
const value = env[ref.env]?.trim();
if (value) return { value, source: `env:${ref.env}` };
}
if (ref.op) {
const value = opRead(ref.op, env).trim();
if (!value || value.split(/\r?\n/).length !== 1) {
throw new CloudTokenError("cloud_token_command_failed", `op read did not print a single token for ${ref.op}`);
}
return { value, source: `op:${ref.op}` };
}
return void 0;
}
function keySourceFor(input) {
const ref = input.endpoint?.key;
const envName = (name) => {
if (!name) return void 0;
return input.env[name]?.trim() ? `env:${name}` : void 0;
};
if (input.mode === "cloud") {
const fromEnv2 = envName(ref?.env);
if (fromEnv2) return fromEnv2;
if (ref?.op) return `op:${ref.op}`;
const fromBindingEnv = envName(input.binding?.tokenEnv);
if (fromBindingEnv) return fromBindingEnv;
if (input.binding?.tokenCommand) return "token-command";
return "missing";
}
const fromAuth = envName("KXM_AUTH_TOKEN");
if (fromAuth) return fromAuth;
const fromEnv = envName(ref?.env);
if (fromEnv) return fromEnv;
if (ref?.op) return `op:${ref.op}`;
if (input.hasSavedProjectToken?.(input.project)) return "hub-env";
return "missing";
}
function describeHubConnection(cwd, env = process.env, hooks = {}) {
const settings = loadHubSettings(cwd, env);
const binding = activeBinding(env);
const mode = settings.mode ?? (binding?.cloud ? "cloud" : "local");
const modeSource = settings.mode ? "config" : binding?.cloud ? "binding" : "default";
const endpoint = endpointFor(mode, settings);
const fromEnv = env.KXM_SERVER_URL?.trim();
const fromConfig = endpoint?.url?.trim();
const fromBinding = binding?.url;
let url = "http://127.0.0.1:7331";
let urlSource = "default";
if (fromEnv) {
url = fromEnv.replace(/\/$/, "");
urlSource = "env";
} else if (fromConfig) {
url = fromConfig.replace(/\/$/, "");
urlSource = "config";
} else if (fromBinding) {
url = fromBinding;
urlSource = "binding";
}
const identity = resolveProjectIdentity(cwd, env, hooks.explicitProject);
const configuredCloudUrl = settings.cloud?.url ?? (binding?.cloud ? binding.url : void 0);
let scope;
if (mode === "cloud") {
const override = fromEnv ? normalizeUrl(fromEnv) : void 0;
const named = configuredCloudUrl ? normalizeUrl(configuredCloudUrl) : void 0;
scope = override && named && override !== named ? hubBindingScope(url) : "remote";
} else {
scope = hubBindingScope(url);
}
return {
...identity,
mode,
modeSource,
url,
urlSource,
scope,
...endpoint ? { endpoint } : {},
...binding ? { binding } : {},
keySource: keySourceFor({
mode,
env,
...endpoint ? { endpoint } : {},
...binding ? { binding } : {},
project: identity.project,
...hooks.hasSavedProjectToken ? { hasSavedProjectToken: hooks.hasSavedProjectToken } : {}
})
};
}
// plugins/kxm/src/hub-env.ts
var HUB_ENV_SCHEMA = "kxm.hub-env.v1";
var HubEnvError = class extends Error {
constructor(message) {
super(message);
this.name = "HubEnvError";
}
};
function resolveUserStateRoot2(env) {
const explicit = env.KXM_STATE_HOME?.trim();
if (explicit) {
if (!isAbsolute7(explicit)) throw new HubEnvError("local_state_root_not_absolute");
return resolve12(explicit);
}
if (process.platform === "win32") {
const localAppData = env.LOCALAPPDATA?.trim();
const base2 = localAppData && isAbsolute7(localAppData) ? localAppData : join21(homedir4(), "AppData", "Local");
return resolve12(base2, "KXM");
}
if (process.platform === "darwin") return resolve12(homedir4(), "Library", "Application Support", "KXM");
const xdgState = env.XDG_STATE_HOME?.trim();
const base = xdgState && isAbsolute7(xdgState) ? xdgState : join21(homedir4(), ".local", "state");
return resolve12(base, "kxm");
}
function hubEnvFile(env = process.env) {
return join21(resolveUserStateRoot2(env), "hub-env.json");
}
function readHubEnvRecord(env = process.env) {
const file = hubEnvFile(env);
if (!existsSync18(file)) return void 0;
let parsed;
try {
parsed = JSON.parse(readFileSync16(file, "utf8"));
} catch (error) {
throw new HubEnvError(`hub env file is malformed at ${file}: ${error instanceof Error ? error.message : String(error)}`);
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new HubEnvError(`hub env file is malformed at ${file}: expected a JSON object`);
}
const record2 = parsed;
if (record2.schema !== HUB_ENV_SCHEMA) {
throw new HubEnvError(`hub env file at ${file} has unsupported schema ${String(record2.schema)}`);
}
if (record2.authToken !== void 0 && (typeof record2.authToken !== "string" || record2.authToken.trim().length === 0)) {
throw new HubEnvError(`hub env file at ${file} has an invalid authToken`);
}
if (record2.projectTokens !== void 0) {
const tokens = record2.projectTokens;
if (!tokens || typeof tokens !== "object" || Array.isArray(tokens)) {
throw new HubEnvError(`hub env file at ${file} has invalid projectTokens`);
}
for (const [project, token] of Object.entries(tokens)) {
if (!project.trim() || typeof token !== "string" || !token.trim()) {
throw new HubEnvError(`hub env file at ${file} has an empty project name or token`);
}
}
}
return {
schema: HUB_ENV_SCHEMA,
createdAt: typeof record2.createdAt === "string" ? record2.createdAt : "",
...record2.authToken !== void 0 ? { authToken: record2.authToken } : {},
...record2.projectTokens !== void 0 ? { projectTokens: record2.projectTokens } : {}
};
}
function cloudModeToken(cwd, env, explicitProject, opRead) {
const connection = describeHubConnection(cwd, env, explicitProject === void 0 ? {} : { explicitProject });
if (connection.mode !== "cloud") return void 0;
const fromConfig = resolveKeyReference(connection.endpoint?.key, env, opRead);
if (fromConfig) return fromConfig.value;
if (connection.binding?.cloud) return resolveCloudHubToken(connection.binding, env);
throw new CloudTokenError(
"cloud_token_missing",
"cloud hub token is missing; the local hub-env token was not used"
);
}
function resolveClientHubAuthToken(env, project, cwd = process.cwd(), opRead) {
const cloud = cloudModeToken(cwd, env, void 0, opRead);
if (cloud) return cloud;
const envToken = env.KXM_AUTH_TOKEN?.trim();
if (envToken) return envToken;
const fromConfig = resolveKeyReference(describeHubConnection(cwd, env).endpoint?.key, env, opRead);
if (fromConfig) return fromConfig.value;
const record2 = readHubEnvRecord(env);
return record2?.projectTokens?.[project]?.trim() || record2?.authToken?.trim() || void 0;
}
// plugins/kxm/src/logger.ts
import { appendFileSync, existsSync as existsSync19, mkdirSync as mkdirSync9, renameSync as renameSync4, statSync as statSync5, unlinkSync as unlinkSync2 } from "node:fs";
import { dirname as dirname12 } from "node:path";
var LOG_LEVEL_PRIORITY = {
debug: 10,
info: 20,
warn: 30,
error: 40
};
var DEFAULT_LOG_MAX_BYTES = 10 * 1024 * 1024;
var DEFAULT_LOG_MAX_FILES = 3;
var SENSITIVE_KEY_PATTERN = /(?:^|_)(?:token|secret|password|apiKey|api_key|authorization|bearer)(?:$|_)/i;
var ALLOWED_EXACT_KEYS = /* @__PURE__ */ new Set(["auth", "authType", "authMethod", "authArgs", "canUpdate", "status"]);
function redactLogValue(val, key) {
if (val === null || val === void 0) return val;
if (typeof val === "string") {
if (key && SENSITIVE_KEY_PATTERN.test(key) && !ALLOWED_EXACT_KEYS.has(key)) {
return "[redacted]";
}
return redactSecrets(val);
}
if (typeof val === "number" || typeof val === "boolean") {
return val;
}
if (Array.isArray(val)) {
return val.map((item) => redactLogValue(item, key));
}
if (typeof val === "object") {
const out = {};
for (const [k, v] of Object.entries(val)) {
out[k] = redactLogValue(v, k);
}
return out;
}
return String(val);
}
function rotateLogFiles(filePath, maxFiles) {
for (let i = maxFiles; i >= 1; i--) {
const current = `${filePath}.${i}`;
if (existsSync19(current)) {
if (i >= maxFiles) {
try {
unlinkSync2(current);
} catch {
}
} else {
try {
renameSync4(current, `${filePath}.${i + 1}`);
} catch {
}
}
}
}
if (existsSync19(filePath)) {
try {
renameSync4(filePath, `${filePath}.1`);
} catch {
}
}
}
function createLogger(options) {
const component = options.component;
const filePath = options.path;
const maxBytes = Math.max(100, options.maxBytes ?? DEFAULT_LOG_MAX_BYTES);
const maxFiles = Math.max(1, options.maxFiles ?? DEFAULT_LOG_MAX_FILES);
const configuredLevel = options.level ?? "info";
const isDaemon = Boolean(options.daemon ?? (process.env.KXM_DAEMON === "1" || process.env.KXM_DAEMON === "true"));
const shouldStdout = options.stdout ?? !isDaemon;
const correlationDefaults = options.correlation ?? {};
let currentSize = 0;
if (filePath && existsSync19(filePath)) {
try {
currentSize = statSync5(filePath).size;
} catch {
currentSize = 0;
}
}
function emit(level, entryOrEvent, extra) {
const minPriority = LOG_LEVEL_PRIORITY[configuredLevel] ?? LOG_LEVEL_PRIORITY.info;
const currentPriority = LOG_LEVEL_PRIORITY[level] ?? LOG_LEVEL_PRIORITY.info;
if (currentPriority < minPriority) return;
let base;
if (typeof entryOrEvent === "string") {
base = { event: entryOrEvent, ...extra };
} else {
base = { ...entryOrEvent, ...extra };
}
const timestamp = typeof base.timestamp === "string" ? base.timestamp : (/* @__PURE__ */ new Date()).toISOString();
delete base.timestamp;
delete base.level;
delete base.component;
const payload = {
timestamp,
level,
component,
...correlationDefaults,
...base
};
const sanitized = redactLogValue(payload);
const line = `${JSON.stringify(sanitized)}
`;
if (filePath) {
const lineBytes = Buffer.byteLength(line, "utf8");
if (currentSize + lineBytes > maxBytes) {
rotateLogFiles(filePath, maxFiles);
currentSize = 0;
}
try {
mkdirSync9(dirname12(filePath), { recursive: true });
appendFileSync(filePath, line, { encoding: "utf8", mode: 384 });
currentSize += lineBytes;
} catch {
}
}
if (shouldStdout) {
process.stdout.write(line);
}
}
const logFn = ((entryOrEvent, extra) => {
let lvl = "info";
if (typeof entryOrEvent === "object" && entryOrEvent !== null && typeof entryOrEvent.level === "string") {
const candidate = entryOrEvent.level.toLowerCase();
if (candidate === "debug" || candidate === "info" || candidate === "warn" || candidate === "error") {
lvl = candidate;
}
}
emit(lvl, entryOrEvent, extra);
});
logFn.info = (entryOrEvent, extra) => emit("info", entryOrEvent, extra);
logFn.warn = (entryOrEvent, extra) => emit("warn", entryOrEvent, extra);
logFn.error = (entryOrEvent, extra) => emit("error", entryOrEvent, extra);
logFn.debug = (entryOrEvent, extra) => emit("debug", entryOrEvent, extra);
logFn.child = (sub) => {
return createLogger({
...options,
component: sub.component ? `${component}.${sub.component}` : component,
correlation: { ...correlationDefaults, ...sub.correlation }
});
};
logFn.close = () => {
};
Object.defineProperty(logFn, "options", {
value: Object.freeze({ ...options }),
writable: false,
enumerable: true
});
return logFn;
}
// plugins/kxm/src/runtime-supervisor.ts
function kxmSupervisorTokenFile(paths) {
return join22(paths.runtimeDir, "supervisor.token");
}
function publishKxmSupervisorToken(paths, token) {
const file = kxmSupervisorTokenFile(paths);
mkdirSync10(dirname13(file), { recursive: true, mode: 448 });
const temp = `${file}.${process.pid}.tmp`;
writeFileSync10(temp, `${token}
`, { encoding: "utf8", mode: 384 });
try {
chmodSync2(temp, 384);
} catch {
}
renameSync5(temp, file);
try {
chmodSync2(file, 384);
} catch {
}
}
function hashKxmSupervisorToken(token) {
return `sha256:${createHash16("sha256").update(`kxm-runtime-supervisor\0${token}`, "utf8").digest("hex")}`;
}
function readKxmSupervisorToken(paths) {
const file = kxmSupervisorTokenFile(paths);
const stat = lstatSync6(file, { throwIfNoEntry: false });
if (!stat) return void 0;
if (stat.isSymbolicLink() || !stat.isFile()) {
throw runtimeError("runtime_path_invalid", file, "supervisor token file must be a regular file, not a link");
}
const token = readFileSync17(file, "utf8").trim();
return token.length >= 32 ? token : void 0;
}
function processAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return error.code === "EPERM";
}
}
var HEARTBEAT_STALE_MS = 15e3;
var SUPERVISOR_ERROR_MAX_AGE_MS = 3e4;
function supervisorErrorFile(paths) {
return join22(paths.runtimeDir, "supervisor.error");
}
function clearSupervisorError(paths) {
const file = supervisorErrorFile(paths);
if (existsSync20(file)) rmSync4(file, { force: true });
}
function recordSupervisorError(paths, message) {
try {
mkdirSync10(paths.runtimeDir, { recursive: true, mode: 448 });
writeFileSync10(supervisorErrorFile(paths), `${message}
`, { encoding: "utf8", mode: 384 });
} catch {
}
}
function readRecentSupervisorError(paths) {
const file = supervisorErrorFile(paths);
const stat = lstatSync6(file, { throwIfNoEntry: false });
if (!stat) return void 0;
const ageMs = Date.now() - stat.mtimeMs;
if (ageMs > SUPERVISOR_ERROR_MAX_AGE_MS) return void 0;
try {
return readFileSync17(file, "utf8").trim();
} catch {
return void 0;
}
}
var SETTLED_RUN_STATUS = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
function kxmSupervisorRecordIsLive(record2) {
return supervisorStatusOf(record2).running;
}
function unsettledRunIds(context) {
const ids = [];
for (const stored of context.eventStore.runsForProject(context.projectId, 1e4)) {
let status = stored.status;
try {
status = projectKxmRunReadOnly(context, stored.runId).status;
} catch {
ids.push(stored.runId);
continue;
}
if (!SETTLED_RUN_STATUS.has(status)) ids.push(stored.runId);
}
return ids;
}
function supervisorStatusOf(record2) {
if (!record2) return { running: false };
const heartbeatAgeMs = Date.now() - Date.parse(record2.heartbeatAt);
const fresh = Number.isFinite(heartbeatAgeMs) && heartbeatAgeMs < HEARTBEAT_STALE_MS;
const alive = record2.state === "running" && fresh && processAlive(record2.pid);
return {
running: alive,
runtimeId: record2.runtimeId,
pid: record2.pid,
port: record2.port,
state: alive ? record2.state : "dead",
heartbeatAt: record2.heartbeatAt,
startedAt: record2.startedAt
};
}
function kxmSupervisorStatus(paths, options = {}) {
if (!existsSync20(paths.registryDb)) return { running: false };
if (options.readOnly) {
const database = openReadOnlyDatabase(paths.registryDb);
try {
database.exec("PRAGMA busy_timeout = 5000");
return supervisorStatusOf(readKxmSupervisorRecord(database));
} finally {
database.close();
}
}
const registry = new KxmRuntimeRegistry(paths.registryDb);
try {
return supervisorStatusOf(registry.supervisor());
} finally {
registry.close();
}
}
async function probeSupervisorWithRetry(port, expectedRuntimeId, token) {
for (let attempt = 0; attempt < 3; attempt += 1) {
if (await probeSupervisor(port, expectedRuntimeId, token)) return true;
if (attempt < 2) await new Promise((resolveWait) => setTimeout(resolveWait, 250));
}
return false;
}
async function probeSupervisor(port, expectedRuntimeId, token, timeoutMs = 750) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const nonce = randomBytes3(16).toString("hex");
const response = await fetch(`http://127.0.0.1:${port}/healthz?nonce=${nonce}`, { signal: controller.signal });
if (!response.ok) return false;
const payload = await response.json();
const expectedProof = hashKxmTokenProof(token, nonce);
return payload.runtimeId === expectedRuntimeId && payload.tokenProof === expectedProof;
} catch {
return false;
} finally {
clearTimeout(timeout);
}
}
function hashKxmTokenProof(token, nonce) {
return createHmac("sha256", token).update(`kxm-runtime-token-proof\0${nonce}`, "utf8").digest("hex");
}
async function attachKxmSupervisor(options = {}) {
const paths = kxmRuntimePaths(options.stateRoot !== void 0 ? { stateRoot: options.stateRoot } : { ...options.env ? { env: options.env } : {} });
const status = kxmSupervisorStatus(paths);
if (!status.running || !status.port || !status.runtimeId) return void 0;
const token = readKxmSupervisorToken(paths);
if (!token) return void 0;
if (!await probeSupervisor(status.port, status.runtimeId, token)) return void 0;
return { runtimeId: status.runtimeId, port: status.port, token, started: false };
}
async function ensureKxmSupervisor(options = {}) {
const paths = kxmRuntimePaths(options.stateRoot !== void 0 ? { stateRoot: options.stateRoot } : { ...options.env ? { env: options.env } : {} });
const status = kxmSupervisorStatus(paths);
if (status.running && status.port) {
for (let attempt = 0; attempt < 3; attempt += 1) {
const token = readKxmSupervisorToken(paths);
if (token && await probeSupervisorWithRetry(status.port, status.runtimeId, token)) {
return { runtimeId: status.runtimeId, port: status.port, token, started: false };
}
if (attempt < 2) await new Promise((resolveWait) => setTimeout(resolveWait, 150));
}
throw runtimeError("runtime_supervisor_unreachable", paths.registryDb, `runtime supervisor pid ${status.pid} is registered as running but cannot be probed`);
}
clearSupervisorError(paths);
const scriptPath = join22(findKxmRepoRoot(import.meta.url), "scripts", "kxm-runtime-supervisor.mjs");
const spawnImpl = options.spawnImpl ?? ((script, env) => {
const child = spawn3(process.execPath, [script], {
detached: true,
stdio: "ignore",
env,
windowsHide: true
});
child.unref();
if (child.pid === void 0) throw runtimeError("runtime_supervisor_spawn_failed", script, "could not spawn the runtime supervisor");
return child.pid;
});
const pid = spawnImpl(scriptPath, {
...process.env,
KXM_STATE_HOME: paths.stateRoot
});
const deadline = Date.now() + 1e4;
while (Date.now() < deadline) {
await new Promise((resolveWait) => setTimeout(resolveWait, 100));
const next = kxmSupervisorStatus(paths);
if (next.running && next.port) {
const token = readKxmSupervisorToken(paths);
if (token && await probeSupervisor(next.port, next.runtimeId, token)) {
return { runtimeId: next.runtimeId, port: next.port, token, started: true };
}
}
const errorDetail = readRecentSupervisorError(paths);
if (errorDetail) {
throw runtimeError("runtime_supervisor_start_failed", scriptPath, `runtime supervisor failed at startup: ${errorDetail}`);
}
}
throw runtimeError("runtime_supervisor_start_failed", scriptPath, `runtime supervisor (pid ${pid}) did not become ready in time`);
}
async function readJsonBody(request, limit = 64 * 1024) {
const chunks = [];
let size = 0;
let tooLarge = false;
for await (const chunk of request) {
const buffer = chunk;
size += buffer.byteLength;
if (size > limit) {
tooLarge = true;
continue;
}
if (!tooLarge) chunks.push(buffer);
}
if (tooLarge) throw runtimeError("runtime_request_too_large", request.url ?? "<request>", "request body exceeds the limit");
if (chunks.length === 0) return {};
try {
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw runtimeError("runtime_request_invalid", request.url ?? "<request>", "request body must be a JSON object");
}
return parsed;
} catch (error) {
if (error instanceof KxmConfigError) throw error;
throw runtimeError("runtime_request_invalid", request.url ?? "<request>", "request body is not valid JSON");
}
}
function sendJson(response, status, payload) {
const body = JSON.stringify(payload);
response.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
response.end(body);
}
var DEFAULT_RUNTIME_STOP_GRACE_MS = 3e4;
var MAX_RUNTIME_STOP_GRACE_MS = 6e5;
function runtimeStopGraceMs(env = process.env) {
const raw = env.KXM_RUNTIME_STOP_GRACE_MS;
if (raw === void 0 || raw.trim() === "") return DEFAULT_RUNTIME_STOP_GRACE_MS;
const parsed = Number(raw.trim());
if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0 || parsed > MAX_RUNTIME_STOP_GRACE_MS) {
process.stderr.write(
`KXM_RUNTIME_STOP_GRACE_MS must be an integer between 0 and ${MAX_RUNTIME_STOP_GRACE_MS} ms (10 minutes); using default ${DEFAULT_RUNTIME_STOP_GRACE_MS}
`
);
return DEFAULT_RUNTIME_STOP_GRACE_MS;
}
return parsed;
}
async function waitForDriveSessions(settled, graceMs) {
if (settled.length === 0) return;
let timeout;
try {
await Promise.race([
Promise.allSettled(settled),
new Promise((resolve15) => {
timeout = setTimeout(resolve15, graceMs);
timeout.unref?.();
})
]);
} finally {
if (timeout !== void 0) clearTimeout(timeout);
}
}
async function driveSessionStillPending(settled) {
let pending = true;
void settled.then(
() => {
pending = false;
},
() => {
pending = false;
}
);
await Promise.resolve();
return pending;
}
var DEFAULT_RUNTIME_SYNC_INTERVAL_MS = 1e4;
var MIN_RUNTIME_SYNC_INTERVAL_MS = 250;
var MAX_RUNTIME_SYNC_INTERVAL_MS = 6e4;
var OUTBOX_PUSH_BATCH = 32;
var OUTBOX_PUSH_BATCH_BYTES = 2e5;
var RUNTIME_SYNC_MAX_BACKOFF_MS = 5 * 6e4;
function runtimeSyncIntervalMs(env = process.env) {
const raw = env.KXM_RUNTIME_SYNC_INTERVAL_MS?.trim();
if (!raw) return DEFAULT_RUNTIME_SYNC_INTERVAL_MS;
const parsed = Number(raw);
if (!Number.isInteger(parsed)) return DEFAULT_RUNTIME_SYNC_INTERVAL_MS;
return Math.min(MAX_RUNTIME_SYNC_INTERVAL_MS, Math.max(MIN_RUNTIME_SYNC_INTERVAL_MS, parsed));
}
function isDurableRefusal(outcome) {
return outcome === "conflict" || outcome === "rejected";
}
function isOversizeRefusal(error) {
return error instanceof HubHttpError && (error.statusCode === 413 || error.code === "sync_batch_too_large" || error.code === "payload_too_large");
}
async function syncKxmOutbox(eventStore, client, options = {}) {
const now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
const batchSize = Math.max(1, options.batchSize ?? OUTBOX_PUSH_BATCH);
const result = { pushed: 0, acked: 0, refused: 0, refusals: [], unconfirmed: 0, blocked: false };
const refuse = (row, code) => {
if (eventStore.refuseOutbox([{ seq: row.seq, code }], now()) === 0) return;
result.refused += 1;
result.refusals.push({ runId: row.runId, sequence: row.sequence, code });
};
const deliver = async (batch) => {
const payload = [];
const sendable = [];
for (const row of batch) {
try {
payload.push(JSON.parse(row.syncEvent));
sendable.push(row);
} catch {
refuse(row, "sync_row_unreadable");
}
}
if (sendable.length === 0) return true;
eventStore.markOutboxAttempted(sendable.map((row) => row.seq), now());
let response;
try {
response = await client.pushSyncEvents(payload);
} catch (error) {
if (isOversizeRefusal(error)) {
if (sendable.length > 1) {
for (const row of sendable) {
if (!await deliver([row])) return false;
}
return true;
}
refuse(sendable[0], "sync_row_too_large");
return true;
}
result.blockedReason = syncFailureText(error);
return false;
}
result.pushed += sendable.length;
const acked = [];
sendable.forEach((row, index) => {
const entry = response.results[index];
const describesRow = entry !== void 0 && (entry.runId === void 0 || entry.runId === row.runId) && (entry.sequence === void 0 || entry.sequence === row.sequence);
if (!entry || !describesRow) {
result.unconfirmed += 1;
return;
}
if (entry.outcome === "accepted" || entry.outcome === "duplicate") acked.push(row.seq);
else if (isDurableRefusal(entry.outcome)) refuse(row, entry.code ?? `sync_${entry.outcome}`);
else result.unconfirmed += 1;
});
result.acked += eventStore.ackOutbox(acked, now());
return true;
};
let afterSeq = 0;
for (; ; ) {
const rows = eventStore.pendingOutbox(batchSize, afterSeq);
if (rows.length === 0) return result;
let byteBudget = OUTBOX_PUSH_BATCH_BYTES;
let sendCount = 0;
for (const row of rows) {
const rowBytes = Buffer.byteLength(row.syncEvent, "utf8") + 64;
if (sendCount > 0 && byteBudget - rowBytes < 0) break;
byteBudget -= rowBytes;
sendCount += 1;
}
const batch = rows.slice(0, Math.max(1, sendCount));
afterSeq = batch[batch.length - 1].seq;
if (!await deliver(batch)) {
result.blocked = true;
return result;
}
}
}
function runtimeHubClientFor(context, env, onBindingWarning) {
let recordUrl;
try {
const loaded = loadHubBinding(env);
if (loaded.warning) onBindingWarning?.(loaded.warning);
recordUrl = loaded.record?.url;
} catch (error) {
if (!(error instanceof HubBindingError)) throw error;
onBindingWarning?.(`${error.message}; falling back to the local hub so sync can continue`);
}
const serverUrl = env.KXM_SERVER_URL?.trim() || recordUrl;
if (!serverUrl) return void 0;
const project = context.projectId;
const authToken = resolveClientHubAuthToken(env, project);
return new RuntimeHubClient({
serverUrl,
project,
runtimeId: context.homeRuntimeId,
...authToken ? { authToken } : {}
});
}
function syncBackoffMs(consecutiveStalls, intervalMs) {
if (consecutiveStalls <= 0) return 0;
return Math.min(RUNTIME_SYNC_MAX_BACKOFF_MS, intervalMs * 2 ** Math.min(5, consecutiveStalls - 1));
}
function syncFailureText(error) {
const code = error instanceof HubHttpError ? `${error.statusCode} ${error.code ?? "error"}` : void 0;
const message = error instanceof Error ? error.message : String(error);
return `${code ? `${code}: ` : ""}${message}`.replace(/(kxm_[A-Za-z0-9_]+|[A-Za-z0-9._-]{40,})/g, "[redacted]").slice(0, 300);
}
function runtimeSupervisorLogFile(paths) {
return join22(paths.runtimeDir, "logs", "kxm-runtime.jsonl");
}
async function startKxmRuntimeSupervisor(options = {}) {
const now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
const env = options.env ?? process.env;
const paths = kxmRuntimePaths(options.stateRoot !== void 0 ? { stateRoot: options.stateRoot } : {});
try {
return await startKxmRuntimeSupervisorInner(paths, options.port, now, env);
} catch (error) {
if (!(error instanceof KxmConfigError && error.issues.some((issue4) => issue4.code === "runtime_supervisor_conflict"))) {
recordSupervisorError(paths, error.message);
}
throw error;
}
}
async function startKxmRuntimeSupervisorInner(paths, requestedPortOption, now, env) {
mkdirSync10(paths.runtimeDir, { recursive: true, mode: 448 });
mkdirSync10(paths.projectsDir, { recursive: true, mode: 448 });
const logger = createLogger({
component: "runtime",
path: runtimeSupervisorLogFile(paths),
stdout: false,
maxBytes: 2 * 1024 * 1024
});
const token = randomBytes3(32).toString("hex");
const tokenHash = hashKxmSupervisorToken(token);
const registry = new KxmRuntimeRegistry(paths.registryDb);
const runtimeId = `rtm_${createHash16("sha256").update(`${paths.stateRoot}\0${process.pid}\0${now()}\0${randomBytes3(16).toString("hex")}`, "utf8").digest("hex").slice(0, 24)}`;
const requestedPort = requestedPortOption ?? 0;
let activeRuntimeId = runtimeId;
const contexts = /* @__PURE__ */ new Map();
const syncStatuses = /* @__PURE__ */ new Map();
const registerSyncCredentials = (context) => {
try {
const hubToken = resolveClientHubAuthToken(env, context.projectId);
if (hubToken) context.eventStore.syncRedactor.register(hubToken);
} catch (error) {
if (!(error instanceof CloudTokenError)) throw error;
}
for (const key of Object.keys(env)) {
if (key.startsWith("KXM_") && (key.endsWith("_TOKEN") || key.endsWith("_KEY")) || key.endsWith("_API_KEY") || key.endsWith("_SECRET")) {
const value = env[key]?.trim();
if (value) context.eventStore.syncRedactor.register(value);
}
}
};
const contextFor = (projectRoot) => {
if (!isAbsolute8(projectRoot)) {
throw runtimeError("runtime_request_invalid", "projectRoot", "projectRoot must be an absolute path");
}
const key = projectRuntimeKey(projectRoot);
const existing = contexts.get(key);
if (existing) return existing;
const context = openKxmRuntimeContext(projectRoot, { homeRuntimeId: activeRuntimeId, stateRoot: paths.stateRoot, logger });
registerSyncCredentials(context);
contexts.set(key, context);
return context;
};
const requireAuth = (request) => {
const header = request.headers.authorization ?? "";
const presented = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
const presentedHash = presented.length > 0 ? Buffer.from(hashKxmSupervisorToken(presented), "utf8") : Buffer.alloc(0);
const expectedHash = Buffer.from(tokenHash, "utf8");
if (presentedHash.length !== expectedHash.length || !timingSafeEqual2(presentedHash, expectedHash)) {
throw runtimeError("runtime_auth_failed", request.url ?? "<request>", "missing or invalid supervisor token");
}
};
const server = createServer((request, response) => {
void (async () => {
try {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
if (request.method === "GET" && url.pathname === "/healthz") {
const nonce = url.searchParams.get("nonce") ?? "";
sendJson(response, 200, {
ok: true,
runtimeId: activeRuntimeId,
state: "running",
// Proof of token knowledge: an impostor that merely binds the
// stale port cannot answer the keyed challenge.
tokenProof: nonce.length > 0 ? hashKxmTokenProof(token, nonce) : void 0
});
return;
}
requireAuth(request);
if (request.method === "POST" && url.pathname === "/v1/shutdown") {
sendJson(response, 200, { ok: true, stopping: true });
setImmediate(() => {
void stop();
});
return;
}
if (request.method === "GET" && url.pathname === "/v1/sync/status") {
const projectRoot = url.searchParams.get("projectRoot");
const statuses = [...syncStatuses.values()].filter((status) => projectRoot === null || status.projectRoot === projectRoot).sort((left, right) => left.projectId.localeCompare(right.projectId));
sendJson(response, 200, { ok: true, runtimeId: activeRuntimeId, projects: statuses });
return;
}
if (request.method === "POST" && url.pathname === "/v1/sync/retry") {
const body = await readJsonBody(request);
const projectRoot = typeof body.projectRoot === "string" ? body.projectRoot : "";
const context = contextFor(projectRoot);
const key = projectRuntimeKey(context.projectRoot);
const retried = context.eventStore.retryRefusedOutbox();
const status = syncStatuses.get(key);
if (status) {
const cleared = { ...status, outbox: context.eventStore.outboxStatus(), consecutiveFailures: 0 };
delete cleared.nextAttemptAt;
syncStatuses.set(key, cleared);
}
logger({ event: "runtime_sync_retry", projectId: context.projectId, retried });
sendJson(response, 200, { ok: true, projectId: context.projectId, retried, outbox: context.eventStore.outboxStatus() });
return;
}
if (request.method === "POST" && url.pathname === "/v1/projects/unregister") {
const body = await readJsonBody(request);
const projectRoot = typeof body.projectRoot === "string" ? body.projectRoot : "";
const force = body.force === true;
if (!projectRoot || !isAbsolute8(projectRoot)) {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: "projectRoot must be an absolute path" });
return;
}
if (!force) {
const key2 = projectRuntimeKey(projectRoot);
const existing2 = contexts.get(key2);
let openRunIds = [];
if (existing2) {
openRunIds = unsettledRunIds(existing2);
} else {
const registration = registry.projectByRoot(projectRoot);
const eventsPath = join22(paths.projectsDir, registration?.projectKey ?? projectRuntimeKey(projectRoot), "run-events.db");
if (registration && existsSync20(eventsPath)) {
const store = new KxmRunEventStore(eventsPath);
try {
openRunIds = store.runsForProject(registration.projectId, 1e4).filter((run) => !SETTLED_RUN_STATUS.has(run.status)).map((run) => run.runId);
} finally {
store.close();
}
}
}
if (openRunIds.length > 0) {
sendJson(response, 409, {
ok: false,
error: "runtime_project_busy",
message: `unsettled run ${openRunIds.join(", ")}`,
runIds: openRunIds
});
return;
}
const laneCount = registry.homeLaneCount(projectRoot);
if (laneCount > 0) {
sendJson(response, 409, {
ok: false,
error: "runtime_project_has_lanes",
message: `home root still has ${laneCount} lane(s)`
});
return;
}
}
const key = projectRuntimeKey(projectRoot);
const existing = contexts.get(key);
const unregistered = registry.unregisterProject(projectRoot);
if (existing) {
contexts.delete(key);
syncStatuses.delete(key);
closeKxmRuntimeContext(existing);
}
sendJson(response, 200, { ok: true, unregistered });
return;
}
if (request.method === "POST" && url.pathname === "/v1/runs") {
const body = await readJsonBody(request);
const projectRoot = typeof body.projectRoot === "string" ? body.projectRoot : "";
const workflowId = typeof body.workflowId === "string" ? body.workflowId : "";
const prompt = typeof body.prompt === "string" ? body.prompt : "";
if (!projectRoot || !workflowId) {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: "projectRoot and workflowId are required" });
return;
}
const context = contextFor(projectRoot);
const bundle = loadKxmProject(projectRoot, {});
const acceptance = acceptKxmRun(context, bundle, {
...typeof body.commandId === "string" && body.commandId.length > 0 ? { commandId: body.commandId } : {},
workflowId,
prompt
});
sendJson(response, 200, {
ok: true,
idempotent: acceptance.idempotent,
run: acceptance.run,
event: acceptance.event
});
return;
}
const runMatch = /^\/v1\/runs\/([A-Za-z0-9_-]+)(?:\/(events|cancel|signal|wait|drive))?$/.exec(url.pathname);
if (runMatch) {
const runId = runMatch[1];
const sub = runMatch[2];
const projectRoot = url.searchParams.get("projectRoot") ?? "";
if (!projectRoot) {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: "projectRoot query parameter is required" });
return;
}
const context = contextFor(projectRoot);
const bundle = loadKxmProject(projectRoot, {});
if (request.method === "GET" && !sub) {
const projected = projectKxmRunReadOnly(context, runId);
const folded = foldStoredKxmRun(context, projected);
const drive = kxmDrivePollProjection(context, runId, folded);
sendJson(response, 200, { ok: true, run: projected, ...drive !== void 0 ? { drive } : {} });
return;
}
if (request.method === "POST" && sub === "drive") {
const body = await readJsonBody(request);
if (body.mode !== "simulated" && body.mode !== "live") {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: "drive mode must be simulated or live" });
return;
}
const run = context.eventStore.run(runId);
if (!run) throw runtimeError("run_unknown", runId, "run not found");
const delayMs = typeof body.delayMs === "number" && body.delayMs > 0 ? body.delayMs : 0;
const createProducer = () => body.mode === "live" ? createKxmOneShotProducer({
projectRoot,
timeoutMs: kxmProjectAdmissionLimits(bundle).agentStepTimeoutMs
}) : createKxmSimulatedProducer(async () => {
if (delayMs > 0) {
await new Promise((r) => setTimeout(r, delayMs));
}
return { outcome: "passed" };
});
let session;
let earlyError;
try {
const scheduler = KxmRunScheduler.for(context, bundle);
const opening = scheduler.openDriveSession(runId, {
mode: body.mode,
allowLimits: false,
liveMode: body.mode === "live",
createProducer
});
opening.catch((err) => {
earlyError = err;
});
session = await opening;
} catch (err) {
earlyError = err;
}
if (earlyError) {
const errStr = String(earlyError);
if (errStr.includes("run_handoff_required")) {
const handoff = earlyError.handoff;
sendJson(response, 409, { ok: false, error: "run_handoff_required", ...handoff !== void 0 ? { handoff } : {} });
return;
}
if (errStr.includes("run_busy") || errStr.includes("scheduler_policy_conflict")) {
sendJson(response, 409, { ok: false, error: "run_busy", message: `run ${runId} is already admitted or queued` });
return;
}
throw earlyError;
}
void session.settled.catch(() => {
});
if (response.writableEnded) return;
sendJson(response, 202, {
ok: true,
status: "accepted",
runId,
driveId: session.driveId,
poll: `/v1/runs/${runId}`,
mode: body.mode
});
return;
}
if (request.method === "GET" && sub === "events") {
const after = Number.parseInt(url.searchParams.get("after") ?? "0", 10);
const events = context.eventStore.events(runId, Number.isFinite(after) && after >= 0 ? after : 0, 500);
sendJson(response, 200, { ok: true, events });
return;
}
if (request.method === "GET" && sub === "drive") {
const run = context.eventStore.run(runId);
if (!run) throw runtimeError("run_unknown", runId, "run not found");
const activeSession = kxmDriveSession(context.eventStore.path, runId);
const session = activeSession ? {
driveId: activeSession.driveId,
mode: activeSession.mode,
openedAt: activeSession.openedAt,
deadlineAt: activeSession.deadlineAt ?? null
} : null;
const receipts = context.eventStore.driveReceiptsForRun(runId, 20);
sendJson(response, 200, { ok: true, session, receipts });
return;
}
if (request.method === "POST" && sub === "cancel") {
const body = await readJsonBody(request);
const result = cancelKxmRun(context, runId, {
...typeof body.commandId === "string" && body.commandId.length > 0 ? { commandId: body.commandId } : {}
});
sendJson(response, 200, { ok: true, idempotent: result.idempotent, run: result.run, events: result.events });
return;
}
if (request.method === "POST" && sub === "signal") {
const body = await readJsonBody(request);
const run = context.eventStore.run(runId);
if (!run) throw runtimeError("run_unknown", runId, "run not found");
const state = foldStoredKxmRun(context, run);
let unblocked = false;
if (state.status === "blocked_uncertain" || state.status === "cancelling" || state.currentStep?.effectState === "blocked_uncertain") {
const action = body.action === "cancel" || body.action === "fail" || body.action === "retry" || body.action === "unblock" ? body.action : "unblock";
const rec = recoverKxmRun(context, runId, {
action,
reason: typeof body.summary === "string" ? body.summary : `signal_${body.signalKey ?? "callback"}`
});
unblocked = rec.unblocked;
}
sendJson(response, 200, { ok: true, runId, signalKey: body.signalKey, status: body.status, unblocked });
return;
}
if (request.method === "POST" && sub === "wait") {
const body = await readJsonBody(request);
const run = context.eventStore.run(runId);
if (!run) throw runtimeError("run_unknown", runId, "run not found");
sendJson(response, 200, { ok: true, runId, stageId: body.stageId, signalKey: body.signalKey, waiting: true });
return;
}
}
const driveMatch = /^\/v1\/drives\/([A-Za-z0-9_-]+)$/.exec(url.pathname);
if (request.method === "GET" && driveMatch) {
const driveId = driveMatch[1];
const projectRoot = url.searchParams.get("projectRoot") ?? "";
if (!projectRoot) {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: "projectRoot query parameter is required" });
return;
}
const context = contextFor(projectRoot);
let receipt;
try {
receipt = context.eventStore.driveReceipt(driveId);
} catch {
sendJson(response, 200, { ok: true, receipt: null, verified: false, divergence: "receipt unreadable" });
return;
}
if (!receipt) {
sendJson(response, 404, { ok: false, error: "drive_receipt_missing", message: "receipt not found" });
return;
}
const runId = receipt.runId;
const stored = context.eventStore.run(runId);
if (!stored) {
sendJson(response, 200, { ok: true, receipt, verified: false, divergence: "run missing" });
return;
}
const state = foldStoredKxmRun(context, stored);
const events = context.eventStore.events(runId, 0, 1e6);
const checked = verifyKxmDriveReceipt(receipt, events, state.status, { runId, driveId });
sendJson(response, 200, {
ok: true,
receipt,
verified: checked.verified,
...checked.divergence !== void 0 ? { divergence: checked.divergence } : {}
});
return;
}
const projectRunsMatch = /^\/v1\/projects\/(prj_[A-Za-z0-9_-]+)\/runs$/.exec(url.pathname);
if (request.method === "GET" && projectRunsMatch) {
const projectRoot = url.searchParams.get("projectRoot") ?? "";
if (!projectRoot) {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: "projectRoot query parameter is required" });
return;
}
const context = contextFor(projectRoot);
const requestedProjectId = projectRunsMatch[1];
if (requestedProjectId !== context.projectId) {
sendJson(response, 400, { ok: false, error: "runtime_request_invalid", message: `project ${requestedProjectId} is not the bound project ${context.projectId}` });
return;
}
const limitText = url.searchParams.get("limit");
const parsedLimit = limitText === null ? 50 : Number(limitText);
const limit = Number.isInteger(parsedLimit) && parsedLimit > 0 ? Math.min(parsedLimit, 1e4) : 50;
const runs = context.eventStore.runsForProject(requestedProjectId, limit).map((stored) => {
try {
return projectKxmRunReadOnly(context, stored.runId);
} catch (error) {
return {
...stored,
projectionError: error instanceof KxmConfigError ? error.issues[0]?.code ?? "runtime_projection_failed" : "runtime_projection_failed"
};
}
});
sendJson(response, 200, { ok: true, runs });
return;
}
sendJson(response, 404, { ok: false, error: "runtime_not_found" });
} catch (error) {
if (error instanceof KxmConfigError) {
const code = error.issues[0]?.code ?? "runtime_error";
const status = code === "runtime_auth_failed" ? 401 : code === "run_unknown" ? 404 : 400;
sendJson(response, status, { ok: false, error: code, issues: error.issues });
return;
}
sendJson(response, 500, { ok: false, error: "runtime_internal" });
}
})();
});
const port = await new Promise((resolvePort, rejectPort) => {
server.once("error", rejectPort);
server.listen(requestedPort, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address !== "object") {
rejectPort(new Error("runtime supervisor did not bind"));
return;
}
resolvePort(address.port);
});
});
const claim = registry.claimSupervisor({ runtimeId, pid: process.pid, port, tokenHash, now: now() });
if (!claim.claimed) {
const existing = claim.record;
const heartbeatAgeMs = Date.now() - Date.parse(existing.heartbeatAt);
const fresh = Number.isFinite(heartbeatAgeMs) && heartbeatAgeMs < HEARTBEAT_STALE_MS;
if (existing.state === "running" && fresh && processAlive(existing.pid)) {
registry.close();
server.close();
throw runtimeError("runtime_supervisor_conflict", paths.registryDb, `runtime supervisor is already managed by PID ${existing.pid}`);
}
try {
const takeover = registry.takeoverSupervisor({ runtimeId, pid: process.pid, port, tokenHash, now: now(), observedDeadPid: existing.pid, observedHeartbeatAt: existing.heartbeatAt });
activeRuntimeId = takeover.runtimeId;
} catch (error) {
registry.close();
server.close();
throw error;
}
}
try {
publishKxmSupervisorToken(paths, token);
clearSupervisorError(paths);
} catch (error) {
registry.close();
server.close();
throw error;
}
const heartbeat = setInterval(() => {
try {
const changes = registry.heartbeat(process.pid, now());
if (changes === 0 && !stopping) {
void stop().finally(() => process.exit(0));
}
} catch {
}
}, 1e3);
heartbeat.unref();
const reopenRegisteredProjects = () => {
for (const reg of registry.projectsForRuntime(activeRuntimeId)) {
const key = projectRuntimeKey(reg.projectRoot);
if (contexts.has(key)) continue;
try {
contextFor(reg.projectRoot);
syncStatuses.delete(key);
} catch (error) {
const reason = syncFailureText(error);
const prior = syncStatuses.get(key);
if (prior === void 0 || prior.lastError !== reason) {
logger.warn({
event: "runtime_sync_context_unavailable",
projectId: reg.projectId,
message: `cannot reopen ${reg.projectRoot}: its outbox rows stay pending`,
reason
});
}
syncStatuses.set(key, {
projectId: reg.projectId,
projectRoot: reg.projectRoot,
homeRuntimeId: activeRuntimeId,
state: "blocked",
outbox: { pending: 0, acked: 0, refused: 0, refusals: [] },
storeReadable: false,
consecutiveFailures: 1,
lastError: reason
});
}
}
};
reopenRegisteredProjects();
const recordSyncStatus = (context, next) => {
const key = projectRuntimeKey(context.projectRoot);
const previous = syncStatuses.get(key);
syncStatuses.set(key, next);
const changed = previous === void 0 || previous.state !== next.state || next.lastError !== void 0 && previous?.lastError !== next.lastError || JSON.stringify(next.outbox.refusals) !== JSON.stringify(previous?.outbox.refusals ?? []);
if (!changed) return;
const stalledState = next.state === "blocked" || next.state === "refusing";
const entry = {
event: stalledState ? "runtime_sync_stalled" : "runtime_sync_state",
projectId: next.projectId,
runtimeId: next.homeRuntimeId,
state: next.state,
pending: next.outbox.pending,
acked: next.outbox.acked,
refused: next.outbox.refused,
...next.outbox.refusals.length > 0 ? { refusals: next.outbox.refusals } : {},
...next.hubUrl ? { hubUrl: next.hubUrl } : {},
...next.lastError ? { reason: next.lastError } : {},
...next.nextAttemptAt ? { nextAttemptAt: next.nextAttemptAt } : {}
};
if (stalledState) logger.warn(entry);
else logger.info(entry);
};
let syncing = false;
let bindingWarning;
const syncTimer = setInterval(() => {
if (syncing || stopping) return;
syncing = true;
void (async () => {
reopenRegisteredProjects();
for (const context of [...contexts.values()]) {
const key = projectRuntimeKey(context.projectRoot);
const prior = syncStatuses.get(key);
if (prior?.nextAttemptAt && Date.parse(prior.nextAttemptAt) > Date.parse(now())) continue;
const base = {
projectId: context.projectId,
projectRoot: context.projectRoot,
homeRuntimeId: context.homeRuntimeId,
outbox: context.eventStore.outboxStatus(),
consecutiveFailures: 0
};
try {
const client = runtimeHubClientFor(context, env, (message) => {
if (bindingWarning === message) return;
bindingWarning = message;
logger.warn({ event: "hub_binding_fallback", message });
});
if (!client) {
recordSyncStatus(context, { ...base, state: "no_hub" });
continue;
}
await client.heartbeat();
const pass = await syncKxmOutbox(context.eventStore, client, { now });
const outbox = context.eventStore.outboxStatus();
const failures = pass.blocked || pass.unconfirmed > 0 ? (prior?.consecutiveFailures ?? 0) + 1 : 0;
const delayMs = syncBackoffMs(failures, runtimeSyncIntervalMs(env));
recordSyncStatus(context, {
...base,
hubUrl: client.options.serverUrl,
outbox,
state: pass.blocked ? "blocked" : outbox.refused > 0 || pass.unconfirmed > 0 ? "refusing" : "ok",
lastCompletedAt: now(),
lastPushed: pass.pushed,
lastAcked: pass.acked,
lastRefused: pass.refused,
lastUnconfirmed: pass.unconfirmed,
consecutiveFailures: failures,
...pass.blockedReason !== void 0 ? { lastError: pass.blockedReason } : {},
...delayMs > 0 ? { nextAttemptAt: new Date(Date.parse(now()) + delayMs).toISOString() } : {}
});
} catch (error) {
const failures = (prior?.consecutiveFailures ?? 0) + 1;
const delayMs = syncBackoffMs(failures, runtimeSyncIntervalMs(env));
recordSyncStatus(context, {
...base,
state: "blocked",
consecutiveFailures: failures,
lastError: syncFailureText(error),
nextAttemptAt: new Date(Date.parse(now()) + delayMs).toISOString()
});
}
}
})().finally(() => {
syncing = false;
});
}, runtimeSyncIntervalMs(env));
syncTimer.unref();
let stopping = false;
const stop = async () => {
if (stopping) return;
stopping = true;
clearInterval(heartbeat);
clearInterval(syncTimer);
try {
registry.markStopping(process.pid, now());
} catch {
}
const openSessions = [...contexts.values()].flatMap((context) => kxmOpenDriveSessions(context.eventStore.path).map((session) => ({ context, session })));
for (const { context, session } of openSessions) {
try {
cancelKxmRun(context, session.runId, { reason: "runtime_shutdown" });
} catch {
}
try {
session.controller.abort();
} catch {
}
}
await waitForDriveSessions(openSessions.map(({ session }) => session.settled), runtimeStopGraceMs());
for (const { context, session } of openSessions) {
if (!await driveSessionStillPending(session.settled)) continue;
recordDriveReceipt(context, session, {
kind: "unsettled",
reason: "runtime_shutdown_grace_expired",
producerId: session.producerId,
producerClosed: false
});
}
for (const context of contexts.values()) closeKxmRuntimeContext(context);
contexts.clear();
logger.close();
const closed = new Promise((resolveStop) => server.close(() => resolveStop()));
server.closeIdleConnections?.();
await closed;
try {
registry.markStopped(process.pid, now());
} catch {
}
registry.close();
};
process.once("SIGINT", () => {
void stop().finally(() => process.exit(0));
});
process.once("SIGTERM", () => {
void stop().finally(() => process.exit(0));
});
return { server, port, runtimeId: activeRuntimeId, stop };
}
async function kxmRuntimeRequest(handle, method, path, body) {
const response = await fetch(`http://127.0.0.1:${handle.port}${path}`, {
method,
headers: {
authorization: `Bearer ${handle.token}`,
...body !== void 0 ? { "content-type": "application/json" } : {}
},
...body !== void 0 ? { body: JSON.stringify(body) } : {}
});
const payload = await response.json();
if (!response.ok) {
const code = typeof payload.error === "string" ? payload.error : "runtime_request_failed";
const message = typeof payload.message === "string" ? payload.message : `runtime request failed with HTTP ${response.status}`;
throw runtimeError(code, path, `${message}${handoffSuffix(payload.handoff)}`);
}
return payload;
}
var HANDOFF_TEXT_MAX = 200;
function handoffSuffix(handoff) {
if (!handoff || typeof handoff !== "object" || Array.isArray(handoff)) return "";
const parts = [];
for (const key of ["reason", "field", "detail"]) {
const value = handoff[key];
if (typeof value === "string" && value.length > 0) parts.push(`${key} ${value.slice(0, HANDOFF_TEXT_MAX)}`);
}
return parts.length > 0 ? ` (handoff ${parts.join("; ")})` : "";
}
// plugins/kxm/src/pi-producer.ts
import { spawn as spawn4 } from "node:child_process";
import { join as join23 } from "node:path";
import { StringDecoder } from "node:string_decoder";
function formatPiSessionKey(params) {
if (params.agentId === "coordinator") {
return `coordinator:${params.runId}`;
}
return `${params.runId}:${params.agentId}:${params.instanceNo ?? 1}:${params.scopeEpoch ?? 1}`;
}
function formatPiSessionDisplayName(params) {
const shortRun = params.runId.length > 8 ? params.runId.slice(0, 8) : params.runId;
if (params.agentId === "coordinator") {
return `coordinator@${shortRun}`;
}
return `${params.agentId}@${shortRun}#${params.instanceNo ?? 1}.${params.scopeEpoch ?? 1}`;
}
function extractText(content) {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
return content.map((part) => typeof part === "object" && part && "text" in part && typeof part.text === "string" ? part.text : "").join("\n");
}
return "";
}
function asJsonObject2(text) {
try {
const parsed = JSON.parse(text);
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
} catch {
return void 0;
}
}
function outcomeField(value) {
const outcome = value.outcome;
return typeof outcome === "string" ? outcome : void 0;
}
function declaredOutcomeOf(text) {
const trimmed = text.trim();
if (!trimmed) return void 0;
const whole = asJsonObject2(trimmed);
if (whole) return outcomeField(whole);
const lines = trimmed.split(/\r?\n/);
let declaration;
for (let index = 0; index < lines.length; index += 1) {
const outcome = outcomeField(asJsonObject2(lines[index].trim()) ?? {});
if (outcome !== void 0) declaration = { index, outcome };
}
if (!declaration) return void 0;
const tail = lines.slice(declaration.index + 1).join("\n");
if (/"outcome"\s*:/.test(tail)) return void 0;
return declaration.outcome;
}
function determineOutcome2(text, allowedOutcomes) {
const declared = declaredOutcomeOf(text);
return declared !== void 0 && allowedOutcomes.includes(declared) ? declared : "failed";
}
var PiSession = class {
key;
displayName;
runId;
agentId;
instanceNo;
scopeEpoch;
sessionDir;
model;
process;
status = "idle";
commandCounter = 0;
pendingCommands = /* @__PURE__ */ new Map();
activePrompt;
lineDecoder = new StringDecoder("utf8");
lineBuffer = "";
constructor(params) {
this.key = params.key;
this.displayName = params.displayName;
this.runId = params.runId;
this.agentId = params.agentId;
this.instanceNo = params.instanceNo;
this.scopeEpoch = params.scopeEpoch;
this.sessionDir = params.sessionDir;
this.model = params.model;
this.process = params.process;
this.attachStdout();
this.attachProcessEvents();
}
isClosed() {
return this.status === "closed";
}
isBusy() {
return this.status === "busy";
}
attachStdout() {
this.process.stdout.on("data", (chunk) => {
this.lineBuffer += this.lineDecoder.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
let newlineIdx;
while ((newlineIdx = this.lineBuffer.indexOf("\n")) !== -1) {
let line = this.lineBuffer.slice(0, newlineIdx);
this.lineBuffer = this.lineBuffer.slice(newlineIdx + 1);
if (line.endsWith("\r")) line = line.slice(0, -1);
const trimmed = line.trim();
if (!trimmed) continue;
try {
const parsed = JSON.parse(trimmed);
this.handleRpcMessage(parsed);
} catch {
}
}
});
}
attachProcessEvents() {
this.process.on("close", (code, signal) => {
this.status = "closed";
const err = new Error(`pi_process_closed: code=${code ?? "null"} signal=${signal ?? "null"}`);
for (const pending of this.pendingCommands.values()) {
pending.reject(err);
}
this.pendingCommands.clear();
if (this.activePrompt) {
this.activePrompt.signalCleanup?.();
this.activePrompt.reject(err);
this.activePrompt = void 0;
}
});
this.process.on("error", (err) => {
this.status = "closed";
for (const pending of this.pendingCommands.values()) {
pending.reject(err);
}
this.pendingCommands.clear();
if (this.activePrompt) {
this.activePrompt.signalCleanup?.();
this.activePrompt.reject(err);
this.activePrompt = void 0;
}
});
}
handleRpcMessage(msg) {
if (msg.type === "response" && typeof msg.id === "string") {
const pending = this.pendingCommands.get(msg.id);
if (pending) {
this.pendingCommands.delete(msg.id);
if (msg.success === false) {
pending.reject(new Error(typeof msg.error === "string" ? msg.error : "rpc_command_failed"));
} else {
pending.resolve(msg);
}
}
return;
}
if (!this.activePrompt) return;
if (msg.type === "message_update") {
if (msg.usage && typeof msg.usage === "object") {
this.updateUsage(msg.usage);
}
} else if (msg.type === "turn_end") {
const message = msg.message;
if (message && message.content !== void 0) {
this.activePrompt.text += `${extractText(message.content)}
`;
}
if (message && message.usage && typeof message.usage === "object") {
this.updateUsage(message.usage);
}
} else if (msg.type === "agent_end") {
const messages = msg.messages;
if (Array.isArray(messages)) {
for (const m of messages) {
if (m && typeof m === "object" && m.role === "assistant") {
const content = m.content;
if (content) this.activePrompt.text += `${extractText(content)}
`;
const usage = m.usage;
if (usage && typeof usage === "object") this.updateUsage(usage);
}
}
}
} else if (msg.type === "agent_settled") {
const active = this.activePrompt;
this.activePrompt = void 0;
this.status = "idle";
active.signalCleanup?.();
const isAborted = active.aborted || active.signal?.aborted;
let outcome;
if (isAborted) {
outcome = "cancelled";
} else {
outcome = determineOutcome2(active.text, active.allowedOutcomes);
}
active.resolve({
outcome,
text: active.text.trim() || (isAborted ? "aborted" : ""),
usage: active.usage
});
}
}
updateUsage(raw) {
if (!this.activePrompt) return;
const u = this.activePrompt.usage;
if (typeof raw.input === "number") u.input = raw.input;
if (typeof raw.output === "number") u.output = raw.output;
if (typeof raw.cacheRead === "number") u.cacheRead = raw.cacheRead;
if (typeof raw.cacheWrite === "number") u.cacheWrite = raw.cacheWrite;
if (typeof raw.totalTokens === "number") u.totalTokens = raw.totalTokens;
if (raw.contextUsage && typeof raw.contextUsage === "object") {
const cu = raw.contextUsage;
u.contextUsage = {
tokens: typeof cu.tokens === "number" ? cu.tokens : void 0,
contextWindow: typeof cu.contextWindow === "number" ? cu.contextWindow : void 0,
percent: typeof cu.percent === "number" ? cu.percent : void 0
};
}
}
async sendCommand(command) {
if (this.status === "closed") {
throw new Error("pi_session_closed");
}
const id = `cmd_${++this.commandCounter}`;
const payload = { ...command, id };
return new Promise((resolve15, reject) => {
this.pendingCommands.set(id, { resolve: resolve15, reject });
try {
this.process.stdin.write(JSON.stringify(payload) + "\n");
} catch (err) {
this.pendingCommands.delete(id);
reject(err instanceof Error ? err : new Error(String(err)));
}
});
}
async prompt(message, allowedOutcomes, signal) {
if (this.status === "closed") {
throw new Error("pi_session_closed");
}
if (this.status === "busy") {
throw new Error("pi_session_busy");
}
if (signal?.aborted) {
return { outcome: "cancelled", text: "aborted", usage: {} };
}
this.status = "busy";
return new Promise((resolve15, reject) => {
let signalCleanup;
if (signal) {
const onAbort = () => {
if (this.activePrompt) {
this.activePrompt.aborted = true;
}
void this.abort().catch(() => {
});
};
signal.addEventListener("abort", onAbort, { once: true });
signalCleanup = () => signal.removeEventListener("abort", onAbort);
}
this.activePrompt = {
resolve: resolve15,
reject,
allowedOutcomes,
text: "",
usage: {},
signal,
signalCleanup,
aborted: false
};
this.sendCommand({ type: "prompt", message }).catch((err) => {
if (this.activePrompt) {
this.activePrompt.signalCleanup?.();
this.activePrompt = void 0;
this.status = "idle";
}
reject(err);
});
});
}
async abort() {
if (this.status === "closed") return;
if (this.activePrompt) {
this.activePrompt.aborted = true;
}
try {
await this.sendCommand({ type: "abort" });
} catch {
}
}
async close() {
if (this.status === "closed") return;
this.status = "closed";
try {
this.process.kill();
} catch {
}
}
};
function createKxmPiProducer(options = {}) {
const sessions = /* @__PURE__ */ new Map();
const defaultModel = options.defaultModel ?? "xai/grok-4.6";
const defaultProvider = options.defaultProvider ?? "xai";
function parseModelString(spec) {
const trimmed = spec.trim();
if (trimmed.includes("/")) {
const idx = trimmed.indexOf("/");
return { provider: trimmed.slice(0, idx).toLowerCase(), model: trimmed.slice(idx + 1) };
}
return { provider: defaultProvider, model: trimmed };
}
function resolveModelForRequest(request) {
if (request.model) {
if (request.provider) {
return { provider: request.provider.toLowerCase(), model: request.model, thinking: request.thinking };
}
const parsed2 = parseModelString(request.model);
return {
provider: request.provider?.toLowerCase() ?? parsed2.provider,
model: parsed2.model,
thinking: request.thinking
};
}
if (options.resolveModel) {
const resolved = options.resolveModel(request.agentId, request.runId);
if (resolved && resolved.model) {
if (resolved.provider) {
return { provider: resolved.provider.toLowerCase(), model: resolved.model, thinking: resolved.thinking };
}
const parsed2 = parseModelString(resolved.model);
return {
provider: resolved.provider?.toLowerCase() ?? parsed2.provider,
model: parsed2.model,
thinking: resolved.thinking
};
}
}
const parsed = parseModelString(defaultModel);
return { provider: parsed.provider, model: parsed.model };
}
async function checkPiAuth(provider, model, signal) {
if (options.inventory) {
const piEntry = options.inventory.harnesses.find((h) => h.id === "pi");
if (!piEntry || !piEntry.detected || piEntry.authenticated === false) {
throw new Error("pi_not_authenticated: pi harness not authenticated in inventory");
}
}
const probeFn = options.probeHarness ?? probeHarnessAssignmentAsync;
const probe = await probeFn({
harness: "pi",
provider,
model,
env: options.env,
signal,
timeoutMs: 1e4
});
if (!probe.detected) {
throw new Error(`pi_not_authenticated: pi harness not detected (${probe.issues.join(", ")})`);
}
if (probe.authenticated !== true) {
throw new Error(`pi_not_authenticated: pi not authenticated for provider ${provider} (${probe.issues.join(", ")})`);
}
}
async function getOrCreateSession(request, model) {
const key = formatPiSessionKey({
runId: request.runId,
agentId: request.agentId,
instanceNo: request.instanceNo,
scopeEpoch: request.scopeEpoch
});
const existing = sessions.get(key);
if (existing && !existing.isClosed()) {
return existing;
}
const displayName = formatPiSessionDisplayName({
runId: request.runId,
agentId: request.agentId,
instanceNo: request.instanceNo,
scopeEpoch: request.scopeEpoch
});
const command = options.piCommand ?? "pi";
const args = ["--mode", "rpc", "--name", displayName];
if (options.sessionDir) {
const safeDirName = key.replace(/[^a-zA-Z0-9_-]/g, "_");
args.push("--session-dir", join23(options.sessionDir, request.runId, safeDirName));
}
if (model) {
args.push("--model", model);
}
let proc;
if (options.spawnProcess) {
proc = options.spawnProcess(command, args, { env: options.env ?? process.env });
} else {
const child = spawn4(command, args, {
env: options.env ?? process.env,
stdio: ["pipe", "pipe", "pipe"]
});
proc = {
stdin: child.stdin,
stdout: child.stdout,
stderr: child.stderr ?? void 0,
kill: (sig) => child.kill(sig),
on: (ev, listener) => {
child.on(ev, listener);
return proc;
}
};
}
const session = new PiSession({
key,
displayName,
runId: request.runId,
agentId: request.agentId,
instanceNo: request.instanceNo ?? 1,
scopeEpoch: request.scopeEpoch ?? 1,
sessionDir: options.sessionDir,
model,
process: proc
});
sessions.set(key, session);
return session;
}
const producer = {
id: "pi",
get sessions() {
return sessions;
},
async produce(request) {
const startTime = Date.now();
const resolved = resolveModelForRequest(request);
await checkPiAuth(resolved.provider, resolved.model, request.signal);
const session = await getOrCreateSession(request, resolved.model);
const promptMessage = request.prompt ?? `Execute step ${request.stepId} (attempt ${request.stepAttempt}) for agent ${request.agentId}. Allowed outcomes: ${request.allowedOutcomes.join(", ")}.`;
let promptResult;
try {
promptResult = await session.prompt(promptMessage, request.allowedOutcomes, request.signal);
} catch (err) {
return Promise.reject(err);
}
const latencyMs = Math.max(0, Date.now() - startTime);
const usage = promptResult.usage;
const tokensIn = typeof usage?.input === "number" ? usage.input : null;
const tokensOut = typeof usage?.output === "number" ? usage.output : null;
const cacheReadTokens = typeof usage?.cacheRead === "number" ? usage.cacheRead : null;
const cacheWriteTokens = typeof usage?.cacheWrite === "number" ? usage.cacheWrite : null;
const contextTokens = typeof usage?.contextUsage?.tokens === "number" ? usage.contextUsage.tokens : tokensIn;
const providerMetadata = {};
const loaded = loadPriceCatalogForEstimate({
priceCatalog: options.priceCatalog,
projectRoot: options.projectRoot
});
if (loaded.unavailable) providerMetadata.priceCatalogUnavailable = true;
if (loaded.stale) providerMetadata.priceCatalogStale = true;
const catalog = loaded.catalog;
const costBasis = "unknown";
const costUsd = null;
if (catalog) {
const calculated = calculateModelCost(catalog, {
model: resolved.model,
provider: resolved.provider,
tokensIn,
tokensOut,
cacheReadTokens,
cacheWriteTokens,
contextTokens
});
if (calculated && Number.isFinite(calculated.costUsd)) {
providerMetadata.listCostUsd = calculated.costUsd;
providerMetadata.listPriceRef = calculated.priceRef;
providerMetadata.listPriceSha256 = catalog.sha256;
}
}
return {
outcome: promptResult.outcome,
costBasis,
costUsd,
tokensIn,
tokensOut,
cacheReadTokens,
cacheWriteTokens,
contextTokens,
latencyMs,
harness: "pi",
provider: resolved.provider,
requestedModel: resolved.model,
effectiveModel: resolved.model,
providerMetadata,
...resolved.thinking !== void 0 ? { thinking: resolved.thinking } : {},
agentRole: request.agentRole ?? request.agentId
};
},
async closeRun(runId) {
const toClose = [];
for (const [key, session] of sessions.entries()) {
if (session.runId === runId) {
toClose.push(session);
sessions.delete(key);
}
}
await Promise.all(toClose.map((s) => s.close()));
},
async close() {
const toClose = [...sessions.values()];
sessions.clear();
await Promise.all(toClose.map((s) => s.close()));
}
};
registerTrustedProducer(producer);
return producer;
}
// plugins/kxm/src/improve.ts
import { createHash as createHash17 } from "node:crypto";
import { existsSync as existsSync21, mkdirSync as mkdirSync11, writeFileSync as writeFileSync11 } from "node:fs";
import { join as join24, relative as relative5, resolve as resolve13 } from "node:path";
var CANDIDATE_SCHEMA = "kxm.candidate.v1";
var IMPROVEMENT_REPORT_SCHEMA = "kxm.improvement-report.v2";
var IMPROVEMENT_REPORT_V1_SCHEMA = "kxm.improvement-report.v1";
function classifyCandidateKind(stepId, agentRole) {
const s = stepId.toLowerCase();
const r = agentRole.toLowerCase();
if (s.includes("verify") || s.includes("gate") || s.includes("test") || s.includes("check") || s.includes("lint") || r === "verifier") {
return "gate";
}
if (s.includes("plan") || s.includes("review") || s.includes("repro") || r === "planner" || r === "reviewer" || r === "critic") {
return "skill";
}
return "workflow-step";
}
function candidateSlug(value) {
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "step";
}
function generateCandidateDiff(kind, stepId, agentRole, workflowId) {
const safeSlug = candidateSlug(stepId);
if (kind === "gate") {
const diff2 = [
"diff --git a/.kxm/gates.yaml b/.kxm/gates.yaml",
"--- a/.kxm/gates.yaml",
"+++ b/.kxm/gates.yaml",
"@@ -1,3 +1,7 @@",
" schema: kxm.gate-registry.v1",
" gates:",
`+ ${safeSlug}:`,
`+ kind: command`,
`+ argv: [npm, run, ${safeSlug}]`,
`+ timeoutMs: 3600000`,
""
].join("\n");
return {
diff: diff2,
declaredOutcome: `Deterministic exit-code verification replacing LLM turn for ${stepId}`,
measure: `100% reduction in LLM inference cost and latency for ${stepId}`,
summary: `Promote deterministic check '${stepId}' (${agentRole}) to coded gate`
};
}
if (kind === "skill") {
const rel2 = `.kxm/skills/candidates/${safeSlug}/SKILL.md`;
const skillContent = [
"---",
`name: ${safeSlug}`,
`description: Governed repeat skill for ${stepId}`,
"---",
"",
`# ${stepId}`,
"",
`Reusable skill instructions for ${stepId} (${agentRole}).`,
""
].join("\n");
const diff2 = [
`diff --git a/${rel2} b/${rel2}`,
"new file mode 100644",
"--- /dev/null",
`+++ b/${rel2}`,
`@@ -0,0 +1,${skillContent.split("\n").length} @@`,
...skillContent.split("\n").map((l) => `+${l}`),
""
].join("\n");
return {
diff: diff2,
declaredOutcome: `Governed reusable skill for ${stepId}`,
measure: `Reduced prompt drift and consistent model guidance for ${stepId}`,
summary: `Consolidate repeated instructions for '${stepId}' (${agentRole}) into a governed skill (consolidation, not a coded step)`
};
}
const rel = `.kxm/workflows/${workflowId !== void 0 ? candidateSlug(workflowId) : safeSlug}.yaml`;
const diff = [
`diff --git a/${rel} b/${rel}`,
`--- a/${rel}`,
`+++ b/${rel}`,
"@@ -1,3 +1,3 @@",
` - id: ${stepId}`,
"- kind: agent",
`- agent: ${agentRole}`,
"+ kind: gate",
`+ gate: ${safeSlug}`,
"diff --git a/.kxm/gates.yaml b/.kxm/gates.yaml",
"--- a/.kxm/gates.yaml",
"+++ b/.kxm/gates.yaml",
"@@ -1,2 +1,6 @@",
" schema: kxm.gate-registry.v1",
" gates:",
`+ ${safeSlug}:`,
"+ kind: command",
`+ argv: [node, scripts/${safeSlug}.mjs]`,
"+ timeoutMs: 600000",
""
].join("\n");
return {
diff,
declaredOutcome: `Coded gate replaces the model turn for ${stepId}; the operator writes scripts/${safeSlug}.mjs`,
measure: `Model cost and latency for ${stepId} drop to zero while its accepted rate holds`,
summary: `Replace the model turn for '${stepId}' (${agentRole}) with a coded gate step`
};
}
function nonEmptyText(value) {
if (typeof value !== "string") return void 0;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : void 0;
}
function roundThree(value) {
return Number(value.toFixed(3));
}
function groupRoutingRecords(records, options = {}) {
const minRecurrence = options.minRecurrence ?? 2;
const minPassRate = options.minPassRate ?? 0.75;
const halfLifeDays = options.halfLifeDays ?? 14;
const now = options.now ?? Date.now();
const raws = records.map((record2) => record2);
const runKeys = raws.map((raw, index) => nonEmptyText(raw.runId) ?? nonEmptyText(raw.workflowRunId) ?? `record:${index}`);
const stepIds = raws.map((raw) => nonEmptyText(raw.stepId) ?? nonEmptyText(raw.stageId) ?? "unknown");
const retriesOf = (raw) => typeof raw.retries === "number" && Number.isFinite(raw.retries) ? raw.retries : 0;
const maxRetries = /* @__PURE__ */ new Map();
raws.forEach((raw, index) => {
const attemptKey = `${runKeys[index]}\0${stepIds[index]}`;
maxRetries.set(attemptKey, Math.max(maxRetries.get(attemptKey) ?? 0, retriesOf(raw)));
});
const map = /* @__PURE__ */ new Map();
raws.forEach((raw, index) => {
const providerMeta = raw.providerMetadata && typeof raw.providerMetadata === "object" && !Array.isArray(raw.providerMetadata) ? raw.providerMetadata : {};
const workflowId = nonEmptyText(providerMeta.workflowId);
const workflowHash = workflowId ?? nonEmptyText(raw.workflowDefinitionSha256) ?? nonEmptyText(providerMeta.workflowDefinitionSha256) ?? nonEmptyText(raw.workflowRunId) ?? nonEmptyText(raw.runId) ?? "standalone";
const stepId = stepIds[index];
const agentRole = nonEmptyText(raw.agentRole) ?? "agent";
const promptHash = nonEmptyText(providerMeta.askSha256) ?? nonEmptyText(raw.rolePromptSha256) ?? "none";
const runKey = runKeys[index];
const key = `${workflowHash}:${stepId}:${agentRole}:${promptHash}`;
let group = map.get(key);
if (!group) {
group = {
key,
workflowHash,
stepId,
agentRole,
promptHash,
costs: [],
latencies: [],
total: 0,
decided: 0,
passed: 0,
undecided: 0,
reworkCount: 0,
weight: 0,
undated: 0,
writes: false,
decidedRuns: /* @__PURE__ */ new Set(),
askRuns: /* @__PURE__ */ new Map(),
evidenceRefs: /* @__PURE__ */ new Set()
};
map.set(key, group);
}
if (group.workflowId === void 0 && workflowId !== void 0) group.workflowId = workflowId;
group.total += 1;
const cost = raw.costUsd;
if (typeof cost === "number" && !Number.isNaN(cost) && cost >= 0) {
group.costs.push(cost);
}
const latency = raw.latencyMs;
if (typeof latency === "number" && !Number.isNaN(latency) && latency >= 0) {
group.latencies.push(latency);
}
const verifierOutcome = raw.verifierOutcome;
const finalOutcome = raw.finalOutcome;
const decided = verifierOutcome !== void 0 && verifierOutcome !== null || finalOutcome !== void 0 && finalOutcome !== null && finalOutcome !== "pending";
if (decided) {
group.decided += 1;
group.decidedRuns.add(runKey);
const ask = nonEmptyText(providerMeta.objectiveSha256) ?? "(unkeyed)";
let askRuns = group.askRuns.get(ask);
if (!askRuns) {
askRuns = /* @__PURE__ */ new Set();
group.askRuns.set(ask, askRuns);
}
askRuns.add(runKey);
const superseded = (maxRetries.get(`${runKey}\0${stepId}`) ?? 0) > retriesOf(raw);
if (!superseded && (verifierOutcome === "passed" || finalOutcome === "accepted" || finalOutcome === "completed")) {
group.passed += 1;
}
} else {
group.undecided += 1;
}
const retries = raw.retries;
if (typeof retries === "number") {
group.reworkCount += retries;
}
const recordedAt = nonEmptyText(raw.recordedAt);
if (recordedAt === void 0 || !Number.isFinite(Date.parse(recordedAt))) group.undated += 1;
group.weight += computeDecayedWeight(recordedAt ?? "", halfLifeDays, now);
if (providerMeta.stepWrites === true) group.writes = true;
const ref = raw.attemptId || raw.runId || raw.workflowRunId || raw.behavioralSha256;
if (ref && group.evidenceRefs.size < 16) {
group.evidenceRefs.add(ref);
}
});
const keyed = [];
for (const group of map.values()) {
const recurrence = group.total;
const meanCost = group.costs.length > 0 ? Number((group.costs.reduce((a, b) => a + b, 0) / group.costs.length).toFixed(4)) : 0;
const meanLatency = group.latencies.length > 0 ? Math.round(group.latencies.reduce((a, b) => a + b, 0) / group.latencies.length) : 0;
const verifyPassRate = group.decided > 0 ? roundThree(group.passed / group.decided) : 0;
const distinctRuns = group.decidedRuns.size;
const askRecurrence = Math.max(0, ...[...group.askRuns.values()].map((runs) => runs.size));
const passes = verifyPassRate >= minPassRate;
const isCandidate = askRecurrence >= minRecurrence && passes && !group.writes;
let excludedReason;
if (!isCandidate && passes) {
if (askRecurrence >= minRecurrence && group.writes) excludedReason = "writes-repository";
else if (distinctRuns >= minRecurrence && askRecurrence < minRecurrence) excludedReason = "ask-not-repeated";
}
const candidateKind = isCandidate ? classifyCandidateKind(group.stepId, group.agentRole) : void 0;
const safeSlug = group.stepId.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 16) || "step";
const keyHash = createHash17("sha256").update(`${group.workflowHash}:${group.stepId}:${group.agentRole}:${group.promptHash}`).digest("hex").slice(0, 10);
const candidateId = isCandidate && candidateKind ? `cand_${candidateKind.replace(/-/g, "_")}_${safeSlug}_${keyHash}` : void 0;
keyed.push({
key: group.key,
row: {
workflowHash: group.workflowHash,
...group.workflowId !== void 0 ? { workflowId: group.workflowId } : {},
stepId: group.stepId,
agentRole: group.agentRole,
promptHash: group.promptHash,
recurrence,
distinctRuns,
askRecurrence,
undecidedRecords: group.undecided,
meanCost,
meanLatency,
verifyPassRate,
rework: group.reworkCount,
weightedRecurrence: roundThree(group.weight),
undatedRecords: group.undated,
costSamples: group.costs.length,
writesRepository: group.writes,
evidenceRefs: [...group.evidenceRefs],
isCandidate,
...excludedReason !== void 0 ? { excludedReason } : {},
...candidateKind !== void 0 ? { candidateKind } : {},
...candidateId !== void 0 ? { candidateId } : {}
}
});
}
return keyed.sort((left, right) => {
const a = left.row;
const b = right.row;
if (a.isCandidate !== b.isCandidate) return a.isCandidate ? -1 : 1;
if (b.weightedRecurrence !== a.weightedRecurrence) return b.weightedRecurrence - a.weightedRecurrence;
if (b.recurrence !== a.recurrence) return b.recurrence - a.recurrence;
return compareCodeUnitIds(a.stepId, b.stepId) || compareCodeUnitIds(left.key, right.key);
}).map((entry) => entry.row);
}
function buildImprovementReport(records, options = {}) {
const projectRoot = options.projectRoot ? resolve13(options.projectRoot) : process.cwd();
const candidatesDir = options.candidatesDir ? resolve13(options.candidatesDir) : join24(projectRoot, ".kxm", "candidates");
const promotionPolicy = options.promotionPolicy ?? "manual_pr";
const groups = groupRoutingRecords(records, options);
const candidates = [];
const promotion = [];
for (const group of groups) {
if (!group.isCandidate || !group.candidateKind || !group.candidateId) continue;
const { diff, declaredOutcome, measure, summary } = generateCandidateDiff(
group.candidateKind,
group.stepId,
group.agentRole,
group.workflowId
);
const diffFileName = `${group.candidateId}.diff`;
const diffFilePath = join24(candidatesDir, diffFileName);
const relDiffPath = relative5(projectRoot, diffFilePath).replace(/\\/g, "/");
const candidate = {
schema: CANDIDATE_SCHEMA,
id: group.candidateId,
kind: group.candidateKind,
summary,
evidenceRefs: group.evidenceRefs.length > 0 ? group.evidenceRefs : ["evidence:telemetry"],
baselineMetrics: {
recurrence: group.recurrence,
meanCost: group.meanCost,
meanLatency: group.meanLatency,
verifyPassRate: group.verifyPassRate,
rework: group.rework
},
declaredOutcome,
measure,
proposedDiffPath: relDiffPath,
status: "proposed",
createdAt: nowIso()
};
if (!options.dryRun) {
if (!existsSync21(candidatesDir)) {
mkdirSync11(candidatesDir, { recursive: true });
}
writeFileSync11(diffFilePath, diff, "utf8");
const jsonFilePath = join24(candidatesDir, `${group.candidateId}.json`);
writeFileSync11(jsonFilePath, JSON.stringify(candidate, null, 2) + "\n", "utf8");
}
candidates.push(candidate);
}
const rowsByCandidate = new Map(groups.flatMap((row) => row.candidateId !== void 0 ? [[row.candidateId, row]] : []));
for (const candidate of candidates) {
const row = rowsByCandidate.get(candidate.id);
promotion.push({
candidateId: candidate.id,
...evaluatePromotionPolicy(candidate, promotionPolicy, {
autoThreshold: options.autoThreshold,
...row ? { costSamples: row.costSamples, distinctRuns: row.distinctRuns } : {}
})
});
}
const routeSwitches = options.routeSwitches?.filter((item) => item.from && item.to) ?? [];
return {
schema: IMPROVEMENT_REPORT_SCHEMA,
createdAt: nowIso(),
reviewDecision: "proposed",
recordsCount: records.length,
groups,
candidates,
promotionPolicy,
promotion,
...routeSwitches.length > 0 ? { routeSwitches: [...routeSwitches] } : {}
};
}
function writeImprovementReport(improvementsDir, report, dryRun = false) {
const stamp = report.createdAt.replace(/[:.]/g, "-");
const path = join24(improvementsDir, `${stamp}.json`);
if (!dryRun) {
mkdirSync11(improvementsDir, { recursive: true });
writeFileSync11(path, `${JSON.stringify(report, null, 2)}
`, { encoding: "utf8" });
}
return path;
}
function formatImprovementReport(report) {
const lines = [
`Improvement Report (${report.recordsCount} record(s), ${report.groups.length} group(s), ${report.candidates.length} candidate(s); promotion policy ${report.promotionPolicy})`,
"",
"Workflow Step Role Prompt Records Runs Asks Weighted Cost ($) Latency (ms) Accepted Rework Candidate",
"------------------------------------------------------------------------------------------------------------------------------------------"
];
for (const g of report.groups) {
const wf = g.workflowHash.slice(0, 12).padEnd(14);
const step = g.stepId.slice(0, 11).padEnd(12);
const role = g.agentRole.slice(0, 11).padEnd(12);
const prompt = g.promptHash.replace(/^sha256:/, "").slice(0, 10).padEnd(12);
const rec = String(g.recurrence).padStart(7);
const runs = String(g.distinctRuns).padStart(5);
const asks = String(g.askRecurrence).padStart(5);
const weighted = g.weightedRecurrence.toFixed(3).padStart(9);
const cost = g.meanCost.toFixed(3).padStart(9);
const lat = String(g.meanLatency).padStart(13);
const accepted = `${(g.verifyPassRate * 100).toFixed(0)}%`.padStart(9);
const rework = String(g.rework).padStart(7);
const cand = g.isCandidate ? `yes (${g.candidateKind})` : g.excludedReason !== void 0 ? `no (${g.excludedReason})` : "no";
lines.push(`${wf} ${step} ${role} ${prompt} ${rec} ${runs} ${asks} ${weighted} ${cost} ${lat} ${accepted} ${rework} ${cand}`);
}
if (report.routeSwitches && report.routeSwitches.length > 0) {
lines.push("");
lines.push(`Route switches (${report.routeSwitches.length}):`);
for (const item of report.routeSwitches) {
const effort = item.effort ? ` effort ${item.effort}` : "";
lines.push(` - ${item.from} -> ${item.to} (${item.reason}${effort}) on ${item.stepId}`);
}
}
if (report.candidates.length > 0) {
const readiness = new Map(report.promotion.map((entry) => [entry.candidateId, entry]));
lines.push("");
lines.push("Emitted Coded-Repeat Candidates:");
for (const c of report.candidates) {
lines.push(` - ${c.id} [${c.kind}]: ${c.summary}`);
lines.push(` Outcome: ${c.declaredOutcome}`);
lines.push(` Measure: ${c.measure}`);
lines.push(` Proposed diff: ${c.proposedDiffPath}`);
const entry = readiness.get(c.id);
if (entry) {
lines.push(` Promotion (${entry.policy}): ${entry.readyForReview ? "ready for review" : "not ready for review"}; ${entry.reason}`);
}
}
lines.push("");
lines.push("Candidates are proposals: readiness never authorizes, and activation is a reviewed Git change.");
}
return lines.join("\n");
}
function evaluatePromotionPolicy(candidate, policy = "manual_pr", options = {}) {
if (policy === "manual_pr") {
return { policy, readyForReview: true, reason: `operator PR applying ${candidate.proposedDiffPath} required` };
}
if (policy === "critic_quorum") {
const receipts = new Set((options.criticReceipts ?? []).map((receipt) => receipt.trim()).filter((receipt) => receipt.length > 0));
return receipts.size >= 2 ? { policy, readyForReview: true, reason: "two critic receipts cited; operator PR still required" } : { policy, readyForReview: false, reason: `awaiting 2 distinct critic receipts (have ${receipts.size})` };
}
if (policy === "auto_threshold") {
const minRuns = options.autoThreshold?.minRuns ?? 10;
const minPassRate = options.autoThreshold?.minPassRate ?? 0.95;
const minCostSavings = options.autoThreshold?.minCostSavings;
const runs = options.distinctRuns ?? candidate.baselineMetrics.recurrence;
const passRate = candidate.baselineMetrics.verifyPassRate;
const costSamples = options.costSamples ?? 0;
const meanCost = candidate.baselineMetrics.meanCost;
const costMet = minCostSavings === void 0 || costSamples > 0 && meanCost >= minCostSavings;
const ready = runs >= minRuns && passRate >= minPassRate && costMet;
const detail = [
`runs=${runs}/${minRuns}`,
`passRate=${passRate}/${minPassRate}`,
...minCostSavings === void 0 ? [] : [`meanCost=${meanCost}/${minCostSavings} over ${costSamples} cost sample(s)`]
].join(", ");
return ready ? { policy, readyForReview: true, reason: `auto-threshold met (${detail}); operator PR still required` } : { policy, readyForReview: false, reason: `auto-threshold not met (${detail})` };
}
return { policy, readyForReview: false, reason: "unknown promotion policy" };
}
// plugins/kxm/src/browser.ts
import { execSync } from "node:child_process";
var VIEWPORT_PRESETS = Object.freeze({
"mobile-sm": { name: "Mobile Small (SE)", category: "mobile", width: 375, height: 667, isMobile: true, hasTouch: true },
"mobile": { name: "Mobile (iPhone 16 / 15 Pro)", category: "mobile", width: 393, height: 852, isMobile: true, hasTouch: true },
"mobile-lg": { name: "Mobile Large (Pro Max)", category: "mobile", width: 430, height: 932, isMobile: true, hasTouch: true },
"pixel": { name: "Google Pixel 8/9", category: "mobile", width: 412, height: 924, isMobile: true, hasTouch: true },
"galaxy": { name: "Samsung Galaxy S24", category: "mobile", width: 360, height: 780, isMobile: true, hasTouch: true },
"tablet": { name: "Tablet (iPad Air / Mini)", category: "tablet", width: 820, height: 1180, isMobile: true, hasTouch: true },
"tablet-lg": { name: "Tablet Large (iPad Pro 12.9)", category: "tablet", width: 1024, height: 1366, isMobile: true, hasTouch: true },
"laptop": { name: "Standard Laptop", category: "laptop", width: 1366, height: 768 },
"macbook-13": { name: "MacBook Air 13", category: "laptop", width: 1440, height: 900 },
"macbook-16": { name: "MacBook Pro 16", category: "laptop", width: 1728, height: 1117 },
"desktop": { name: "Desktop FHD (1080p)", category: "desktop", width: 1920, height: 1080 },
"desktop-2k": { name: "Desktop QHD (1440p)", category: "desktop", width: 2560, height: 1440 },
"desktop-4k": { name: "Desktop 4K UHD", category: "desktop", width: 3840, height: 2160 }
});
function resolveViewportDimensions(presetOrDims) {
if (!presetOrDims) {
return { width: 1920, height: 1080 };
}
if (typeof presetOrDims === "string") {
const matched = VIEWPORT_PRESETS[presetOrDims.toLowerCase()];
if (matched) {
return { width: matched.width, height: matched.height };
}
return { width: 1920, height: 1080 };
}
return presetOrDims;
}
var SteelAuthConfigError = class extends Error {
constructor(message) {
super(message);
this.name = "SteelAuthConfigError";
}
};
var SteelAuthRedirectError = class extends Error {
status;
host;
constructor(status, host) {
super(
`Steel request was redirected (${status}) to ${host}. Send Authorization: Basic via STEEL_AUTH_BASIC or STEEL_AUTH_USER and STEEL_AUTH_TOKEN. A Bearer token is not accepted.`
);
this.name = "SteelAuthRedirectError";
this.status = status;
this.host = host;
}
};
var LEGACY_STEEL_AUTH_WARNING = "kxm: STEEL_API_KEY is deprecated for Steel. Steel and Caddy do not enforce it. Set STEEL_AUTH_HEADER, or STEEL_AUTH_BASIC, or STEEL_AUTH_USER and STEEL_AUTH_TOKEN. Those override STEEL_API_KEY. Send Authorization on the request, not in the URL.\n";
var legacySteelAuthWarned = false;
function resetLegacySteelAuthWarningForTests() {
legacySteelAuthWarned = false;
}
function warnLegacySteelAuth() {
if (legacySteelAuthWarned) return;
legacySteelAuthWarned = true;
process.stderr.write(LEGACY_STEEL_AUTH_WARNING);
}
function firstNonEmpty(...values) {
for (const value of values) {
const trimmed = value?.trim();
if (trimmed) return trimmed;
}
return void 0;
}
function normalizeAuthorization(raw) {
if (/[\r\n]/.test(raw)) {
throw new SteelAuthConfigError("Steel authorization value contains a line break.");
}
const value = raw.trim();
if (!value) {
throw new SteelAuthConfigError("Steel authorization value is empty.");
}
const basicPrefix = /^basic\s+(.+)$/i.exec(value);
if (basicPrefix) {
const credential = basicPrefix[1] ?? "";
if (!credential || /\s/.test(credential)) {
throw new SteelAuthConfigError("Steel Basic credential must be a single base64 token.");
}
return `Basic ${credential}`;
}
if (/\s/.test(value)) {
return value;
}
return `Basic ${value}`;
}
function resolveSteelAuthorization(overrides) {
const header = firstNonEmpty(overrides?.authHeader, overrides?.authorization, process.env.STEEL_AUTH_HEADER);
if (header) return normalizeAuthorization(header);
const basic = firstNonEmpty(overrides?.authBasic, process.env.STEEL_AUTH_BASIC);
if (basic) return normalizeAuthorization(basic);
const user = firstNonEmpty(overrides?.authUser, process.env.STEEL_AUTH_USER);
const token = firstNonEmpty(overrides?.authToken, process.env.STEEL_AUTH_TOKEN);
if (user || token) {
if (!user || !token) {
throw new SteelAuthConfigError(
"Steel Basic auth needs both STEEL_AUTH_USER and STEEL_AUTH_TOKEN, or STEEL_AUTH_BASIC."
);
}
return `Basic ${Buffer.from(`${user}:${token}`, "utf8").toString("base64")}`;
}
return void 0;
}
function steelRequestHeaders(config) {
if (config.authorization) {
return { Authorization: config.authorization };
}
if (config.apiKey) {
return { "x-steel-api-key": config.apiKey };
}
return {};
}
function steelAuthRedirectError(res) {
let host = "the identity provider";
const location = res.headers.get("location");
if (location) {
try {
host = new URL(location, "https://id.kxmd.dev").host;
} catch {
host = "the identity provider";
}
}
return new SteelAuthRedirectError(res.status, host);
}
function resolvePassCliApiKey(execFn = (cmd) => execSync(cmd, { encoding: "utf8", stdio: ["pipe", "pipe", "ignore"], timeout: 5e3 })) {
if (typeof process === "undefined" || process.env.USE_PASS_CLI === "false") {
return void 0;
}
if (process.env.PASS_CLI_OUTPUT_MOCK) {
try {
const parsed = JSON.parse(process.env.PASS_CLI_OUTPUT_MOCK);
const extraFields = parsed?.item?.content?.extra_fields || [];
const customSections = parsed?.item?.content?.content?.Custom?.sections || [];
const sectionFields = customSections.flatMap((s) => s.section_fields || []);
const allFields = [...extraFields, ...sectionFields];
return allFields.find((f) => f.name === "STEEL_API_KEY")?.content?.Hidden;
} catch {
return void 0;
}
}
try {
const output = execFn(
'pass-cli item view --vault-name "AI Provider Keys" --item-title "Steel Browser (KontextMind DOKS)" --output json'
);
const parsed = JSON.parse(output);
const extraFields = parsed?.item?.content?.extra_fields || [];
const customSections = parsed?.item?.content?.content?.Custom?.sections || [];
const sectionFields = customSections.flatMap((s) => s.section_fields || []);
const allFields = [...extraFields, ...sectionFields];
return allFields.find((f) => f.name === "STEEL_API_KEY")?.content?.Hidden;
} catch {
return void 0;
}
}
function resolveSteelConfig(overrides) {
const apiUrl = overrides?.apiUrl || process.env.STEEL_API_URL || "https://steel.kontextmind.com";
const authorization = resolveSteelAuthorization(overrides);
let apiKey;
if (!authorization) {
apiKey = overrides?.apiKey || process.env.STEEL_API_KEY || resolvePassCliApiKey();
if (apiKey) warnLegacySteelAuth();
}
const uiUrl = overrides?.uiUrl || (overrides?.apiUrl ? `${overrides.apiUrl.replace(/\/$/, "")}/ui` : void 0) || process.env.STEEL_UI_URL || `${apiUrl.replace(/\/$/, "")}/ui`;
return {
apiUrl: apiUrl.replace(/\/$/, ""),
apiKey,
authorization,
uiUrl,
timeoutMs: overrides?.timeoutMs || 3e5
// 5 minutes default
};
}
function formatCDPEndpoint(session, config) {
const baseApi = config.apiUrl;
const urlObj = new URL(baseApi);
const isSecure = urlObj.protocol === "https:";
const wsProtocol = isSecure ? "wss:" : "ws:";
const host = urlObj.host;
const searchParams = new URLSearchParams();
searchParams.set("sessionId", session.id);
if (!config.authorization && config.apiKey) {
searchParams.set("apiKey", config.apiKey);
}
return `${wsProtocol}//${host}/v1/devtools?${searchParams.toString()}`;
}
function formatCDPConnect(session, config) {
return {
url: formatCDPEndpoint(session, config),
headers: steelRequestHeaders(config)
};
}
var DEFAULT_OBSCURA_CDP_URL = "http://127.0.0.1:9222";
var DEFAULT_OBSCURA_PORT = 9222;
function obscuraListenPort() {
const raw = process.env.OBSCURA_PORT?.trim() ?? "";
if (raw === "") return DEFAULT_OBSCURA_PORT;
if (!/^[0-9]+$/.test(raw)) {
throw new Error(`OBSCURA_PORT must be an integer from 1 to 65535 (received ${JSON.stringify(process.env.OBSCURA_PORT)})`);
}
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(`OBSCURA_PORT must be an integer from 1 to 65535 (received ${JSON.stringify(process.env.OBSCURA_PORT)})`);
}
return port;
}
function resolveObscuraCdpEndpoint() {
const explicit = process.env.OBSCURA_CDP_URL?.trim() ?? "";
if (explicit !== "") return explicit;
const port = obscuraListenPort();
if (port === DEFAULT_OBSCURA_PORT) return DEFAULT_OBSCURA_CDP_URL;
return `http://127.0.0.1:${port}`;
}
function resolveBrowserCdpConnect(session, config) {
const browser = (process.env.KXM_BROWSER ?? "").trim().toLowerCase();
if (browser === "" || browser === "obscura") {
return { url: resolveObscuraCdpEndpoint(), headers: {} };
}
if (browser === "steel") {
if (!session?.id) {
throw new Error("KXM_BROWSER=steel requires a Steel session id");
}
return formatCDPConnect(session, config ?? resolveSteelConfig());
}
throw new Error(`Unsupported KXM_BROWSER value ${JSON.stringify(process.env.KXM_BROWSER)}; expected "obscura" or "steel"`);
}
function resolveBrowserCdpEndpoint(session, config) {
return resolveBrowserCdpConnect(session, config).url;
}
async function connectBrowserOverCdp(connectOverCDP, session, config) {
const { url, headers } = resolveBrowserCdpConnect(session, config);
if (Object.keys(headers).length === 0) return connectOverCDP(url);
return connectOverCDP(url, { headers });
}
function sanitizeLogOutput(input) {
if (typeof input === "string") {
const redacted = input.replace(/apiKey=[^&\s]+/gi, "apiKey=[REDACTED]").replace(/([?&]authorization=)[^&\s]+/gi, "$1[REDACTED]").replace(/authorization:\s*(?:basic\s+)?\S+/gi, "authorization: [REDACTED]").replace(/\bBasic\s+(?:[A-Za-z0-9+/]*[+/=0-9][A-Za-z0-9+/]*={0,2})/g, "Basic [REDACTED]").replace(/steel_[a-f0-9]+/g, "steel_[REDACTED]");
return redacted;
}
if (Array.isArray(input)) {
return input.map(sanitizeLogOutput);
}
if (input !== null && typeof input === "object") {
const copy = {};
for (const [k, v] of Object.entries(input)) {
if (/key|secret|token|auth|password/i.test(k) && typeof v === "string") {
copy[k] = "[REDACTED]";
} else {
copy[k] = sanitizeLogOutput(v);
}
}
return copy;
}
return input;
}
function createAnnotationFeedback(feedback) {
return {
...feedback,
capturedAt: feedback.capturedAt || (/* @__PURE__ */ new Date()).toISOString()
};
}
function formatAnnotationFeedbackPrompt(feedback) {
let output = `## Visual Feedback & Section Annotation
`;
output += `- **Target URL**: ${feedback.url}
`;
if (feedback.sessionId) {
output += `- **Session ID**: ${feedback.sessionId}
`;
}
if (feedback.sectionSelector) {
output += `- **Section Target Selector**: \`${feedback.sectionSelector}\`
`;
}
if (feedback.screenshotPath) {
output += `- **Screenshot Artifact**: \`${feedback.screenshotPath}\`
`;
}
output += `- **Captured At**: ${feedback.capturedAt}
`;
output += `### Summary
${feedback.overallSummary}
`;
if (feedback.annotations.length > 0) {
output += `### Annotated Elements & Notes
`;
feedback.annotations.forEach((item, idx) => {
output += `${idx + 1}. **${item.label}**`;
if (item.severity) {
output += ` [${item.severity.toUpperCase()}]`;
}
output += `
- **Note**: ${item.note}
`;
if (item.selector) {
output += ` - **Selector**: \`${item.selector}\`
`;
}
if (item.boundingBox) {
output += ` - **Region (Box)**: x=${item.boundingBox.x}, y=${item.boundingBox.y}, w=${item.boundingBox.width}, h=${item.boundingBox.height}
`;
}
});
output += `
`;
}
if (feedback.requestedChanges.length > 0) {
output += `### Actionable Change List
`;
feedback.requestedChanges.forEach((change, idx) => {
output += `- [ ] ${change}
`;
});
}
return output;
}
var SteelClient = class {
config;
activeSessions = /* @__PURE__ */ new Map();
constructor(config) {
this.config = resolveSteelConfig(config);
}
getConfig() {
return { ...this.config };
}
/**
* URL and headers for `chromium.connectOverCDP(url, { headers })`.
* The URL omits credentials when Authentik Basic auth is configured.
*/
cdpConnectOptions(session) {
return formatCDPConnect(session, this.config);
}
headers() {
return {
"Content-Type": "application/json",
...steelRequestHeaders(this.config)
};
}
async steelFetch(url, init) {
const headers = {
...this.headers(),
...init.headers
};
const res = await fetch(url, { ...init, headers, redirect: "manual" });
if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") {
throw steelAuthRedirectError(res);
}
return res;
}
/**
* Launch a new Steel browser session.
*/
async createSession(options) {
const timeoutMs = options?.timeoutMs ?? this.config.timeoutMs ?? 3e5;
const body = {
timeout: timeoutMs
};
const dimensions = options?.dimensions || (options?.viewportPreset ? resolveViewportDimensions(options.viewportPreset) : void 0);
if (dimensions) {
body.dimensions = dimensions;
}
if (options?.userAgent) {
body.userAgent = options.userAgent;
}
if (options?.proxy) {
body.proxy = options.proxy;
}
const res = await this.steelFetch(`${this.config.apiUrl}/v1/sessions`, {
method: "POST",
body: JSON.stringify(body)
});
if (!res.ok) {
const errText = sanitizeLogOutput(await res.text());
throw new Error(`Failed to create Steel session (${res.status}): ${errText}`);
}
const data = await res.json();
const session = {
id: data.id,
createdAt: data.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
status: "live",
state: "AGENT_CONTROL",
websocketUrl: data.websocketUrl || "",
debugUrl: data.debugUrl || "",
debuggerUrl: data.debuggerUrl || "",
sessionViewerUrl: data.sessionViewerUrl || `${this.config.uiUrl}?sessionId=${data.id}`,
timeoutMs,
lastActiveAt: Date.now(),
activeController: "agent",
userAgent: data.userAgent
};
this.activeSessions.set(session.id, session);
return session;
}
/**
* Get details of an existing session.
*/
async getSession(sessionId) {
const res = await this.steelFetch(`${this.config.apiUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
method: "GET"
});
if (res.status === 404) {
const cached = this.activeSessions.get(sessionId);
if (cached) {
cached.state = "EXPIRED";
cached.status = "released";
cached.activeController = "none";
}
return null;
}
if (!res.ok) {
throw new Error(`Failed to fetch Steel session (${res.status})`);
}
const data = await res.json();
const existing = this.activeSessions.get(sessionId);
const session = {
id: data.id,
createdAt: data.createdAt,
status: data.status,
state: existing?.state ?? (data.status === "live" ? "AGENT_CONTROL" : "RELEASED"),
websocketUrl: data.websocketUrl || existing?.websocketUrl || "",
debugUrl: data.debugUrl || existing?.debugUrl || "",
debuggerUrl: data.debuggerUrl || existing?.debuggerUrl || "",
sessionViewerUrl: existing?.sessionViewerUrl || `${this.config.uiUrl}?sessionId=${data.id}`,
timeoutMs: data.timeout || existing?.timeoutMs || 3e5,
lastActiveAt: Date.now(),
activeController: existing?.activeController ?? (data.status === "live" ? "agent" : "none"),
userAgent: data.userAgent
};
this.activeSessions.set(session.id, session);
return session;
}
/**
* Request human takeover for MFA, login, or consent.
* Pauses agent automation and sets state to HUMAN_CONTROL.
*/
requestHumanTakeover(sessionId, reason) {
const session = this.activeSessions.get(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not tracked or already released`);
}
if (session.state === "RELEASED" || session.state === "EXPIRED" || session.state === "FAILED") {
throw new Error(`Cannot initiate takeover on session in state ${session.state}`);
}
session.state = "HUMAN_CONTROL";
session.activeController = "human";
session.takeoverReason = reason;
session.lastActiveAt = Date.now();
const takeoverUrl = `${this.config.uiUrl}?sessionId=${encodeURIComponent(sessionId)}`;
const instructions = `[HUMAN TAKEOVER REQUIRED]
Reason: ${reason}
Session ID: ${session.id}
Takeover URL: ${takeoverUrl}
Instructions for Operator:
1. Open the URL above to access the session UI.
2. Perform the required authentication / MFA / consent action.
3. Return to the terminal and signal completion. Automation is paused until you confirm.`;
return {
session,
takeoverUrl,
instructions
};
}
/**
* Signal that human takeover is complete.
* Moves state to VERIFY_AUTHENTICATION before transitioning back to AGENT_CONTROL.
*/
signalHumanComplete(sessionId) {
const session = this.activeSessions.get(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not tracked or already released`);
}
if (session.state !== "HUMAN_CONTROL") {
throw new Error(`Session ${sessionId} is not in HUMAN_CONTROL state (currently ${session.state})`);
}
session.state = "VERIFY_AUTHENTICATION";
session.activeController = "agent";
session.lastActiveAt = Date.now();
return {
session,
state: session.state
};
}
/**
* Confirm authentication verification passed and restore AGENT_CONTROL.
*/
confirmAuthenticationVerified(sessionId) {
const session = this.activeSessions.get(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not tracked or already released`);
}
if (session.state !== "VERIFY_AUTHENTICATION") {
throw new Error(`Session ${sessionId} is not in VERIFY_AUTHENTICATION state (currently ${session.state})`);
}
session.state = "AGENT_CONTROL";
session.activeController = "agent";
session.takeoverReason = void 0;
session.lastActiveAt = Date.now();
return session;
}
/**
* Gracefully release a session.
*/
async releaseSession(sessionId) {
try {
const res = await this.steelFetch(`${this.config.apiUrl}/v1/sessions/${encodeURIComponent(sessionId)}/release`, {
method: "POST"
});
const session = this.activeSessions.get(sessionId);
if (session) {
session.status = "released";
session.state = "RELEASED";
session.activeController = "none";
}
this.activeSessions.delete(sessionId);
return res.ok;
} catch (error) {
if (error instanceof SteelAuthRedirectError) throw error;
this.activeSessions.delete(sessionId);
return false;
}
}
/**
* Perform a direct stateless scrape without manual session management.
*/
async scrape(url) {
const res = await this.steelFetch(`${this.config.apiUrl}/v1/scrape`, {
method: "POST",
body: JSON.stringify({ url })
});
if (!res.ok) {
const err = sanitizeLogOutput(await res.text());
throw new Error(`Scrape failed (${res.status}): ${err}`);
}
return res.json();
}
/**
* Perform a direct screenshot action.
*/
async screenshot(url, fullPage = false) {
const res = await this.steelFetch(`${this.config.apiUrl}/v1/screenshot`, {
method: "POST",
body: JSON.stringify({ url, fullPage })
});
if (!res.ok) {
const err = sanitizeLogOutput(await res.text());
throw new Error(`Screenshot failed (${res.status}): ${err}`);
}
return res.json();
}
/**
* Detect and list orphaned or timed-out active sessions.
*/
async checkOrphanedSessions(maxIdleMs = 6e5) {
const res = await this.steelFetch(`${this.config.apiUrl}/v1/sessions`, {
method: "GET"
});
if (!res.ok) {
return [];
}
const data = await res.json();
const remoteSessions = data.sessions || [];
const now = Date.now();
const orphaned = [];
for (const rs of remoteSessions) {
if (rs.status === "live" || rs.status === "idle") {
const tracked = this.activeSessions.get(rs.id);
if (!tracked && rs.duration > maxIdleMs) {
orphaned.push(rs.id);
} else if (tracked && now - tracked.lastActiveAt > maxIdleMs && tracked.state !== "HUMAN_CONTROL") {
orphaned.push(rs.id);
}
}
}
return orphaned;
}
};
// plugins/kxm/src/modes.ts
var import_yaml13 = __toESM(require_dist(), 1);
import { existsSync as existsSync22, readFileSync as readFileSync19 } from "node:fs";
import { join as join25 } from "node:path";
var DEFAULT_MODES_CONFIG = Object.freeze({
schema: "kxm.modes.v1",
majorModes: {
coder: {
description: "First-pass implementation, bug fixing, and test authoring",
baseTools: ["read", "edit", "write", "bash"],
contextFiles: ["AGENTS.md"],
thinkingLevel: "medium",
model: "grok/grok-4.6"
},
planner: {
description: "High-level architectural planning, scoping, and decomposition",
baseTools: ["read", "grep", "find"],
contextFiles: ["plans/implementation-plan.md"],
thinkingLevel: "high",
model: "claude/fable"
},
auditor: {
description: "Security, compliance, and code quality verification",
baseTools: ["read", "grep"],
contextFiles: ["SECURITY.md"],
thinkingLevel: "high",
model: "codex/gpt-5.6-sol"
},
browser: {
description: "Web application exploration, screenshotting, and UI testing",
baseTools: ["read", "bash"],
contextFiles: ["docs/guides/browser-automation.md"],
thinkingLevel: "medium",
model: "grok/grok-4.6"
}
},
domains: {
git: {
description: "Git version control operations",
tools: ["git_status", "git_diff", "git_commit"],
promptSnippet: "Follow git branch conventions; never commit directly to main."
},
k8s: {
description: "Kubernetes cluster inspection and deployment",
tools: ["kubectl_get", "kubectl_describe"],
promptSnippet: "Target local dev cluster; verify namespaces before mutating."
},
database: {
description: "Database queries and schema verification",
tools: ["sqlite_query", "sqlite_schema"],
promptSnippet: "Database is SQLite at .kxm/state/kxm.db; use read-only queries."
},
browser: {
description: "Remote Steel browser sessions and visual testing",
tools: ["steel_session", "steel_scrape", "steel_screenshot"],
promptSnippet: "Playwright tests use Obscura. Steel is remote browsing and takeover through Caddy and Authentik; send Authorization, never a credential in the URL."
}
}
});
function estimateTokens(charCount) {
return Math.ceil(charCount / 3.8);
}
function loadModesConfig(projectRoot) {
if (!projectRoot) {
return DEFAULT_MODES_CONFIG;
}
const modesPath = join25(projectRoot, ".kxm", "modes.yaml");
if (!existsSync22(modesPath)) {
return DEFAULT_MODES_CONFIG;
}
try {
const raw = readFileSync19(modesPath, "utf8");
const parsed = (0, import_yaml13.parse)(raw);
if (parsed && parsed.schema === "kxm.modes.v1" && parsed.majorModes) {
return {
schema: "kxm.modes.v1",
majorModes: { ...DEFAULT_MODES_CONFIG.majorModes, ...parsed.majorModes },
domains: { ...DEFAULT_MODES_CONFIG.domains, ...parsed.domains }
};
}
} catch {
}
return DEFAULT_MODES_CONFIG;
}
function resolveActiveMode(config, majorModeName = "coder", domainNames = []) {
const major = config.majorModes[majorModeName] || config.majorModes["coder"] || DEFAULT_MODES_CONFIG.majorModes["coder"];
const tools = new Set(major.baseTools);
const contextFiles = new Set(major.contextFiles || []);
const promptSnippets = [];
const enabledDomains = [];
if (config.domains) {
for (const dName of domainNames) {
const d = config.domains[dName.toLowerCase().trim()];
if (d) {
enabledDomains.push(dName.toLowerCase().trim());
d.tools.forEach((t) => tools.add(t));
(d.contextFiles || []).forEach((f) => contextFiles.add(f));
if (d.promptSnippet) {
promptSnippets.push(d.promptSnippet);
}
}
}
}
return {
majorMode: majorModeName,
enabledDomains,
tools: Array.from(tools),
contextFiles: Array.from(contextFiles),
promptSnippets,
thinkingLevel: major.thinkingLevel,
model: major.model || "grok/grok-4.6"
};
}
var CATALOG_DATE_RE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
function boundedCatalogDate(value) {
return typeof value === "string" && CATALOG_DATE_RE.test(value) ? value : void 0;
}
function catalogDateForStatus(loaded, injected, projectRoot) {
const fromLoaded = boundedCatalogDate(loaded.catalog?.date);
if (fromLoaded) return fromLoaded;
const fromInjected = boundedCatalogDate(injected?.date);
if (fromInjected) return fromInjected;
if (!loaded.stale) return void 0;
try {
return boundedCatalogDate(loadPriceCatalog(projectRoot)?.date);
} catch {
return void 0;
}
}
function describePriceCatalogStatus(loaded, catalogDate) {
if (loaded.stale) {
return {
catalogStatus: "stale",
catalogReason: catalogDate ? `price catalog stale (dated ${catalogDate})` : "price catalog stale"
};
}
if (loaded.unavailable) {
return { catalogStatus: "corrupt", catalogReason: "price catalog corrupt" };
}
if (!loaded.catalog) {
return { catalogStatus: "missing", catalogReason: "price catalog missing" };
}
return { catalogStatus: "verified", catalogReason: "price catalog verified" };
}
function formatExplainCost(value, footprint, suffix = "") {
if (value !== null) return `$${value.toFixed(4)}${suffix}`;
return footprint.catalogStatus === "verified" ? "unmetered/unknown" : footprint.catalogReason;
}
function calculatePromptFootprint(resolved, projectRoot = process.cwd(), catalog) {
const breakdown = [];
const baseSystemPromptChars = 3200;
breakdown.push({
name: `Base System Prompt (${resolved.majorMode})`,
chars: baseSystemPromptChars,
estimatedTokens: estimateTokens(baseSystemPromptChars)
});
for (const relPath of resolved.contextFiles) {
const fullPath = join25(projectRoot, relPath);
let chars = 0;
if (existsSync22(fullPath)) {
try {
chars = readFileSync19(fullPath, "utf8").length;
} catch {
chars = 0;
}
}
if (chars === 0) {
chars = 1500;
}
breakdown.push({
name: `Context File: ${relPath}`,
chars,
estimatedTokens: estimateTokens(chars)
});
}
if (resolved.promptSnippets.length > 0) {
const snippetChars = resolved.promptSnippets.join("\n").length;
breakdown.push({
name: `Domain Prompts (${resolved.enabledDomains.join(", ")})`,
chars: snippetChars,
estimatedTokens: estimateTokens(snippetChars)
});
}
const toolSchemaChars = resolved.tools.length * 650;
breakdown.push({
name: `Tool Schemas (${resolved.tools.length} active tools)`,
chars: toolSchemaChars,
estimatedTokens: estimateTokens(toolSchemaChars)
});
const totalChars = breakdown.reduce((sum, item) => sum + item.chars, 0);
const totalTokens = breakdown.reduce((sum, item) => sum + item.estimatedTokens, 0);
const maxContextWindow = 2e5;
const contextWindowRatio = Math.round(totalTokens / maxContextWindow * 1e3) / 10;
const loaded = loadPriceCatalogForEstimate(
catalog ? { priceCatalog: catalog } : { projectRoot }
);
const catalogInfo = describePriceCatalogStatus(
loaded,
catalogDateForStatus(loaded, catalog, projectRoot)
);
const cat = loaded.catalog;
const rawModel = resolved.model || "grok/grok-4.6";
const [prov, mod] = rawModel.includes("/") ? rawModel.split("/", 2) : [void 0, rawModel];
const inputCost = cat ? calculateModelCost(cat, {
model: mod || rawModel,
...prov !== void 0 ? { provider: prov } : {},
tokensIn: totalTokens,
tokensOut: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0
}) : void 0;
const cacheReadCost = cat ? calculateModelCost(cat, {
model: mod || rawModel,
...prov !== void 0 ? { provider: prov } : {},
tokensIn: 0,
tokensOut: 0,
cacheReadTokens: totalTokens,
cacheWriteTokens: 0
}) : void 0;
const outputEstimateCost = cat ? calculateModelCost(cat, {
model: mod || rawModel,
...prov !== void 0 ? { provider: prov } : {},
tokensIn: 0,
tokensOut: 1e3,
cacheReadTokens: 0,
cacheWriteTokens: 0
}) : void 0;
return {
majorMode: resolved.majorMode,
enabledDomains: resolved.enabledDomains,
model: resolved.model || "grok/grok-4.6",
breakdown,
totalChars,
totalTokens,
contextWindowRatio,
projectedCost: {
inputCostUsd: inputCost?.costUsd ?? null,
cacheReadCostUsd: cacheReadCost?.costUsd ?? null,
outputCostEstimateUsd: outputEstimateCost?.costUsd ?? null
},
catalogStatus: catalogInfo.catalogStatus,
catalogReason: catalogInfo.catalogReason
};
}
function formatModesExplainReport(footprint) {
const divider = "\u2550".repeat(60);
const subDivider = "\u2500".repeat(60);
let out = `
${divider}
`;
out += `KXM PRE-FLIGHT CONTEXT EXPLAIN
`;
out += `${divider}
`;
out += `Major Mode: ${footprint.majorMode}
`;
out += `Enabled Domains: ${footprint.enabledDomains.length > 0 ? footprint.enabledDomains.join(", ") : "(none)"}
`;
out += `Target Model: ${footprint.model}
`;
out += `Catalog status: ${footprint.catalogReason}
`;
out += `CONTEXT BREAKDOWN:
`;
for (const item of footprint.breakdown) {
const padName = item.name.padEnd(38, " ");
const tokenStr = `${item.estimatedTokens.toLocaleString()} tokens`.padStart(16, " ");
out += ` \u2022 ${padName} ${tokenStr}
`;
}
out += `${subDivider}
`;
const totalPad = `TOTAL PROMPT FOOTPRINT:`.padEnd(38, " ");
const totalStr = `${footprint.totalTokens.toLocaleString()} tokens`.padStart(16, " ");
out += ` ${totalPad} ${totalStr} (${footprint.contextWindowRatio}% of 200k window)
`;
out += `PROJECTED COSTS (per turn):
`;
out += ` \u2022 Initial Turn Input Cost: ${formatExplainCost(footprint.projectedCost.inputCostUsd, footprint)}
`;
out += ` \u2022 Subsequent Cache-Read Cost: ${formatExplainCost(footprint.projectedCost.cacheReadCostUsd, footprint, " (approx 90% savings)")}
`;
out += ` \u2022 Output Estimate (1k tokens): ${formatExplainCost(footprint.projectedCost.outputCostEstimateUsd, footprint)}
`;
out += `${divider}
`;
return out;
}
// plugins/kxm/src/ssh-remote.ts
import { spawnSync as spawnSync8 } from "node:child_process";
import { existsSync as existsSync23, mkdirSync as mkdirSync12, readFileSync as readFileSync20, readdirSync as readdirSync11, rmSync as rmSync5, statSync as statSync6 } from "node:fs";
import { homedir as homedir5 } from "node:os";
import { join as join26, resolve as resolve14 } from "node:path";
var MAX_SSH_OUTPUT_BYTES = 50 * 1024;
var MAX_SSH_OUTPUT_LINES = 2e3;
var DEFAULT_SOCKET_DIR = ".kxm/run/ssh-sockets";
var DEFAULT_CONTROL_PERSIST = "10m";
function truncateSshOutput(raw) {
let text = raw;
let truncated = false;
if (Buffer.byteLength(text, "utf-8") > MAX_SSH_OUTPUT_BYTES) {
const buf = Buffer.from(text, "utf-8");
text = buf.subarray(0, MAX_SSH_OUTPUT_BYTES).toString("utf-8");
truncated = true;
}
const lines = text.split("\n");
if (lines.length > MAX_SSH_OUTPUT_LINES) {
text = lines.slice(0, MAX_SSH_OUTPUT_LINES).join("\n");
truncated = true;
}
if (truncated) {
text += `
[kxm: ssh output truncated to ${MAX_SSH_OUTPUT_BYTES / 1024}KB / ${MAX_SSH_OUTPUT_LINES} lines]`;
}
return { text, truncated };
}
function parseSshConfig(configPath) {
const targetPath = configPath ?? join26(homedir5(), ".ssh", "config");
if (!existsSync23(targetPath)) {
return [];
}
try {
const content = readFileSync20(targetPath, "utf-8");
const lines = content.split("\n");
const hosts = [];
let currentHosts = [];
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line || line.startsWith("#")) continue;
const spaceIdx = line.search(/\s/);
if (spaceIdx === -1) continue;
const key = line.slice(0, spaceIdx).trim().toLowerCase();
const value = line.slice(spaceIdx + 1).trim();
if (key === "host") {
const aliases = value.split(/\s+/).filter((a) => a !== "*");
currentHosts = [];
for (const alias of aliases) {
const entry = { alias, identityFiles: [] };
currentHosts.push(entry);
hosts.push(entry);
}
} else if (currentHosts.length > 0) {
for (const currentHost of currentHosts) {
if (key === "hostname") {
currentHost.hostName = value;
} else if (key === "user") {
currentHost.user = value;
} else if (key === "port") {
const p = Number.parseInt(value, 10);
if (!Number.isNaN(p)) currentHost.port = p;
} else if (key === "proxyjump") {
currentHost.proxyJump = value;
} else if (key === "identityfile") {
currentHost.identityFiles = currentHost.identityFiles ?? [];
currentHost.identityFiles.push(value);
}
}
}
}
return hosts;
} catch {
return [];
}
}
function resolveSshHostG(host, execFn = spawnSync8) {
try {
const result = execFn("ssh", ["-G", host], { encoding: "utf-8" });
if (result.status !== 0 || !result.stdout) {
return { alias: host, hostName: host };
}
const lines = String(result.stdout).split("\n");
const info = { alias: host, identityFiles: [] };
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) continue;
const spaceIdx = line.indexOf(" ");
if (spaceIdx === -1) continue;
const key = line.slice(0, spaceIdx).toLowerCase();
const value = line.slice(spaceIdx + 1).trim();
if (key === "hostname") {
info.hostName = value;
} else if (key === "user") {
info.user = value;
} else if (key === "port") {
const p = Number.parseInt(value, 10);
if (!Number.isNaN(p)) info.port = p;
} else if (key === "proxyjump") {
if (value && value !== "none") info.proxyJump = value;
} else if (key === "identityfile") {
info.identityFiles = info.identityFiles ?? [];
info.identityFiles.push(value);
}
}
return info;
} catch {
return { alias: host, hostName: host };
}
}
function ensureSocketDir(socketDir = DEFAULT_SOCKET_DIR) {
const resolved = resolve14(socketDir);
if (!existsSync23(resolved)) {
mkdirSync12(resolved, { recursive: true, mode: 448 });
}
return resolved;
}
function buildSshArgs(options) {
const socketDir = ensureSocketDir(options.socketDir ?? DEFAULT_SOCKET_DIR);
const controlPath = join26(socketDir, "%C");
const persist2 = options.controlPersist ?? DEFAULT_CONTROL_PERSIST;
const args = [
"-o",
`ControlMaster=auto`,
"-o",
`ControlPath=${controlPath}`,
"-o",
`ControlPersist=${persist2}`
];
if (options.batchMode !== false) {
args.push("-o", "BatchMode=yes");
}
if (options.strictHostKey !== false) {
args.push("-o", "StrictHostKeyChecking=yes");
}
if (options.extraArgs) {
args.push(...options.extraArgs);
}
assertPinnedSshHostKeyPolicy(args);
args.push(options.host);
return args;
}
function checkControlSocket(host, socketDir = DEFAULT_SOCKET_DIR, execFn = spawnSync8) {
const resolvedDir = ensureSocketDir(socketDir);
const controlPath = join26(resolvedDir, "%C");
try {
const result = execFn("ssh", ["-O", "check", "-o", `ControlPath=${controlPath}`, host], {
encoding: "utf-8"
});
return result.status === 0;
} catch {
return false;
}
}
function closeControlSocket(host, socketDir = DEFAULT_SOCKET_DIR, execFn = spawnSync8) {
const resolvedDir = ensureSocketDir(socketDir);
const controlPath = join26(resolvedDir, "%C");
try {
const result = execFn("ssh", ["-O", "stop", "-o", `ControlPath=${controlPath}`, host], {
encoding: "utf-8"
});
return result.status === 0;
} catch {
return false;
}
}
function pruneSocketDir(socketDir = DEFAULT_SOCKET_DIR) {
const resolvedDir = ensureSocketDir(socketDir);
let removed = 0;
try {
const entries = readdirSync11(resolvedDir);
for (const entry of entries) {
const fullPath = join26(resolvedDir, entry);
try {
const stat = statSync6(fullPath);
if (stat.isSocket()) {
rmSync5(fullPath, { force: true });
removed++;
}
} catch {
}
}
} catch {
}
return removed;
}
function executeSshRun(params) {
const startTime = Date.now();
const execSyncFn = params.execFn ?? spawnSync8;
if (params.action === "info") {
if (params.host) {
const hostInfo = resolveSshHostG(params.host, execSyncFn);
return {
ok: true,
action: "info",
host: params.host,
resolvedHost: hostInfo.hostName ?? params.host,
user: hostInfo.user,
port: hostInfo.port,
hosts: [hostInfo],
durationMs: Date.now() - startTime
};
}
const discovered = parseSshConfig();
return {
ok: true,
action: "info",
hosts: discovered,
durationMs: Date.now() - startTime
};
}
if (!params.host) {
return {
ok: false,
action: params.action,
error: 'Parameter "host" is required for command and file actions.',
durationMs: Date.now() - startTime
};
}
const host = params.host;
const socketDir = params.socket_dir ?? DEFAULT_SOCKET_DIR;
const wasSocketActive = checkControlSocket(host, socketDir, execSyncFn);
if (params.action === "command") {
if (!params.command) {
return {
ok: false,
action: "command",
host,
error: 'Parameter "command" is required for command action.',
durationMs: Date.now() - startTime
};
}
try {
assertCommandSeatbelt(params.command);
} catch (err) {
return {
ok: false,
action: "command",
host,
error: err.message,
durationMs: Date.now() - startTime
};
}
let remoteCommand = params.command;
let inputStdin = void 0;
if (params.sudo) {
const sudoPwd = params.sudo_password ?? params.password;
if (sudoPwd) {
inputStdin = `${sudoPwd}
`;
remoteCommand = `sudo -S -p '' -- sh -c ${JSON.stringify(params.command)}`;
} else {
remoteCommand = `sudo -- sh -c ${JSON.stringify(params.command)}`;
}
}
const useSshPass = Boolean(params.password);
const sshArgs = buildSshArgs({
host,
socketDir,
controlPersist: params.control_persist,
batchMode: !useSshPass,
strictHostKey: params.strict_host_key
});
sshArgs.push("--", remoteCommand);
const spawnEnv = { ...process.env };
let binary = "ssh";
let finalArgs = sshArgs;
if (useSshPass && params.password) {
binary = "sshpass";
finalArgs = ["-e", "ssh", ...sshArgs];
spawnEnv.SSHPASS = params.password;
}
try {
const result = execSyncFn(binary, finalArgs, {
encoding: "utf-8",
env: spawnEnv,
input: inputStdin,
timeout: params.timeout_ms ?? 12e4,
maxBuffer: 10 * 1024 * 1024
});
const stdoutRaw = String(result.stdout || "");
const stderrRaw = String(result.stderr || "");
const sanitizedStderr = stderrRaw.replace(/\[sudo\] password for [^:]+:\s*/gi, "");
const stdoutTrunc = truncateSshOutput(stdoutRaw);
const stderrTrunc = truncateSshOutput(sanitizedStderr);
return {
ok: result.status === 0,
action: "command",
host,
exitCode: result.status ?? 1,
stdout: stdoutTrunc.text,
stderr: stderrTrunc.text,
truncated: stdoutTrunc.truncated || stderrTrunc.truncated,
socketReused: wasSocketActive,
durationMs: Date.now() - startTime,
error: result.error ? result.error.message : void 0
};
} catch (err) {
return {
ok: false,
action: "command",
host,
error: err.message,
durationMs: Date.now() - startTime
};
}
}
if (params.action === "file") {
if (!params.file_path) {
return {
ok: false,
action: "file",
host,
error: 'Parameter "file_path" is required for file action.',
durationMs: Date.now() - startTime
};
}
const filePath = params.file_path;
const op = params.file_op ?? "write";
if (op === "read") {
const readCmd = params.sudo ? `sudo cat ${JSON.stringify(filePath)}` : `cat ${JSON.stringify(filePath)}`;
return executeSshRun({
...params,
action: "command",
command: readCmd
});
}
const content = params.file_content ?? "";
const redirectOp = op === "append" ? ">>" : ">";
const writeCmd = params.sudo ? `sudo tee ${op === "append" ? "-a " : ""}${JSON.stringify(filePath)} > /dev/null` : `cat ${redirectOp} ${JSON.stringify(filePath)}`;
const useSshPass = Boolean(params.password);
const sshArgs = buildSshArgs({
host,
socketDir,
controlPersist: params.control_persist,
batchMode: !useSshPass,
strictHostKey: params.strict_host_key
});
sshArgs.push("--", writeCmd);
const spawnEnv = { ...process.env };
let binary = "ssh";
let finalArgs = sshArgs;
if (useSshPass && params.password) {
binary = "sshpass";
finalArgs = ["-e", "ssh", ...sshArgs];
spawnEnv.SSHPASS = params.password;
}
try {
const result = execSyncFn(binary, finalArgs, {
encoding: "utf-8",
env: spawnEnv,
input: content,
timeout: params.timeout_ms ?? 6e4
});
return {
ok: result.status === 0,
action: "file",
host,
exitCode: result.status ?? 1,
stdout: String(result.stdout || ""),
stderr: String(result.stderr || ""),
fileProcessed: filePath,
bytesProcessed: Buffer.byteLength(content, "utf-8"),
socketReused: wasSocketActive,
durationMs: Date.now() - startTime,
error: result.error ? result.error.message : void 0
};
} catch (err) {
return {
ok: false,
action: "file",
host,
error: err.message,
durationMs: Date.now() - startTime
};
}
}
return {
ok: false,
action: params.action,
error: `Unknown action: ${params.action}`,
durationMs: Date.now() - startTime
};
}
// plugins/kxm/src/subagent-control.ts
import { randomUUID as randomUUID5 } from "node:crypto";
var SUBAGENT_TYPES = Object.freeze([
"general",
"Explore",
"Plan",
"Reviewer",
"Auditor"
]);
var DEFAULT_SUBAGENT_MODELS = Object.freeze({
general: "grok/grok-4.6",
Explore: "openrouter/qwen/qwen3-coder-plus",
Plan: "claude/fable",
Reviewer: "openai/gpt-5.6-sol",
Auditor: "claude/fable"
});
function narrowSubagentTools(requestedTools, parentTools) {
if (!requestedTools || requestedTools.length === 0) {
return parentTools ? [...parentTools] : ["read", "grep", "find"];
}
if (!parentTools || parentTools.length === 0) {
return [...requestedTools];
}
const parentSet = new Set(parentTools);
const narrowed = [];
for (const tool of requestedTools) {
if (parentSet.has(tool)) {
narrowed.push(tool);
}
}
if (narrowed.length === 0 && requestedTools.length > 0) {
throw new Error(
`Cannot spawn subagent: requested tools [${requestedTools.join(", ")}] expand beyond parent capabilities.`
);
}
return narrowed;
}
var SubagentManager = class {
subagents = /* @__PURE__ */ new Map();
/**
* Spawns a new managed subagent with strict capability boundaries.
*/
spawn(params) {
if (!params.prompt || !params.prompt.trim()) {
throw new Error('Subagent "prompt" is required.');
}
if (!params.description || !params.description.trim()) {
throw new Error('Subagent "description" is required.');
}
const type = params.type ?? "general";
const model = params.model ?? DEFAULT_SUBAGENT_MODELS[type] ?? "grok/grok-4.6";
const thinking = params.thinking ?? "low";
const allowedTools = narrowSubagentTools(params.allowed_tools, params.parent_tools);
const id = `ag_${randomUUID5().replaceAll("-", "").slice(0, 10)}`;
const now = (/* @__PURE__ */ new Date()).toISOString();
const record2 = {
id,
description: params.description.trim(),
type,
model,
thinking,
allowedTools,
status: params.background === false ? "completed" : "running",
turnsMax: params.turns ?? 10,
turnsCompleted: 0,
prompt: params.prompt.trim(),
createdAt: now,
updatedAt: now,
steeringMessages: []
};
this.subagents.set(id, record2);
return record2;
}
/**
* Dispatches an action from the `agent_control` tool.
*/
control(params) {
const action = params.action;
if (action === "info") {
const kind = params.kind ?? "active";
if (kind === "types") {
return {
ok: true,
action: "info",
types: SUBAGENT_TYPES
};
}
if (kind === "models") {
return {
ok: true,
action: "info",
result: JSON.stringify(DEFAULT_SUBAGENT_MODELS)
};
}
const active = Array.from(this.subagents.values()).map((ag) => ({
id: ag.id,
description: ag.description,
type: ag.type,
status: ag.status
}));
return {
ok: true,
action: "info",
activeAgents: active
};
}
if (!params.agent_id) {
return {
ok: false,
action,
error: 'Parameter "agent_id" is required for result, steer, and stop actions.'
};
}
const agent = this.subagents.get(params.agent_id);
if (!agent) {
return {
ok: false,
action,
agent_id: params.agent_id,
error: `Subagent "${params.agent_id}" not found.`
};
}
if (action === "result") {
return {
ok: true,
action: "result",
agent_id: agent.id,
status: agent.status,
result: agent.output ?? `[Subagent is currently ${agent.status}]`
};
}
if (action === "steer") {
if (!params.message || !params.message.trim()) {
return {
ok: false,
action: "steer",
agent_id: agent.id,
error: 'Parameter "message" is required for steer action.'
};
}
if (agent.status === "completed" || agent.status === "stopped" || agent.status === "failed") {
return {
ok: false,
action: "steer",
agent_id: agent.id,
error: `Cannot steer subagent "${agent.id}" because it is already ${agent.status}.`
};
}
agent.steeringMessages.push({
text: params.message.trim(),
injectedAt: (/* @__PURE__ */ new Date()).toISOString(),
processed: false
});
agent.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
return {
ok: true,
action: "steer",
agent_id: agent.id,
status: agent.status,
steered: true
};
}
if (action === "stop") {
agent.status = "stopped";
agent.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
return {
ok: true,
action: "stop",
agent_id: agent.id,
status: "stopped",
stopped: true
};
}
return {
ok: false,
action,
error: `Unknown control action "${action}".`
};
}
/**
* Retrieves an agent record by ID.
*/
get(agentId) {
return this.subagents.get(agentId);
}
/**
* Marks a subagent as completed with output.
*/
complete(agentId, output) {
const agent = this.subagents.get(agentId);
if (agent) {
agent.status = "completed";
agent.output = output;
agent.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
}
}
/**
* Returns all active running subagents.
*/
listActive() {
return Array.from(this.subagents.values()).filter(
(ag) => ag.status === "running" || ag.status === "pending" || ag.status === "blocked"
);
}
};
export {
BUILTIN_HARNESSES,
BUILTIN_HARNESS_IDS,
CANDIDATE_SCHEMA,
DEFAULT_CONTROL_PERSIST,
DEFAULT_HARNESS,
DEFAULT_LOG_MAX_BYTES,
DEFAULT_LOG_MAX_FILES,
DEFAULT_MODES_CONFIG,
DEFAULT_OBSCURA_CDP_URL,
DEFAULT_RUNTIME_STOP_GRACE_MS,
DEFAULT_RUNTIME_SYNC_INTERVAL_MS,
DEFAULT_SOCKET_DIR,
DEFAULT_SUBAGENT_MODELS,
DRIVE_RECEIPT_MAX_BYTES,
IMPROVEMENT_REPORT_SCHEMA,
IMPROVEMENT_REPORT_V1_SCHEMA,
KXM_ABSENT_MEMORY_REVISION,
KXM_BACKUP_CEILINGS,
KXM_DEFAULT_AGENT_STEP_TIMEOUT_MS,
KXM_DRIVE_RECEIPT_SCHEMA,
KXM_EVENT_STORE_SCHEMA_VERSION,
KXM_EVENT_STORE_TABLE_NAMES,
KXM_MIN_AGENT_STEP_TIMEOUT_MS,
KXM_REGISTRY_SCHEMA_VERSION,
KXM_RUN_EVENT_SCHEMA,
KxmRunEventStore,
KxmRuntimeRegistry,
LOG_LEVEL_PRIORITY,
MAX_RUNTIME_STOP_GRACE_MS,
MAX_SSH_OUTPUT_BYTES,
MAX_SSH_OUTPUT_LINES,
NATIVE_HARNESS_PROVIDERS,
PI_ALLOWED_PROVIDERS,
PI_NATIVE_BRAKE_PROVIDERS,
PiSession,
SAFE_HARNESS_COMMAND_ID,
SUBAGENT_TYPES,
SteelAuthConfigError,
SteelAuthRedirectError,
SteelClient,
SubagentManager,
TRANSACTION_BUSY_BACKOFF_MS,
VIEWPORT_PRESETS,
WIN_NPM_INNER_EXE,
acceptKxmRun,
applyRestorePlan,
assertClosedGateObservation,
assertDatabaseFile,
assertKxmConfigError,
attachKxmSupervisor,
backupDatabaseFile,
buildImprovementReport,
buildSshArgs,
calculatePromptFootprint,
cancelKxmRun,
checkControlSocket,
checkIntegrity,
checkMemoryRevisionDrift,
checkedParent,
checkpointWal,
classifyCandidateKind,
closeControlSocket,
closeKxmRuntimeContext,
computeGateEvidenceOutcome,
computeKxmMemoryRevision,
connectBrowserOverCdp,
createAnnotationFeedback,
createBackup,
createKxmOneShotProducer,
createKxmPiProducer,
createLogger,
databaseError,
defaultSpawn,
discoverProjectStores,
eligibleHarnesses,
ensureKxmSupervisor,
ensureSocketDir,
ensureWalJournalMode,
estimateTokens,
evaluatePromotionPolicy,
executeSshRun,
fileSha256,
findWinNpmInnerExe,
foldStoredKxmRun,
formatAnnotationFeedbackPrompt,
formatCDPConnect,
formatCDPEndpoint,
formatHarnessInventory,
formatHarnessUpdate,
formatImprovementReport,
formatModesExplainReport,
formatPiSessionDisplayName,
formatPiSessionKey,
gateRowContentHash,
groupRoutingRecords,
harnessCommandCandidates,
harnessSpawnUsesShell,
hashKxmDriveLog,
hashKxmSupervisorToken,
hashKxmTokenProof,
isKnownHarnessId,
isKxmRuntimeContextClosed,
isTransactionContention,
isWindowsHarnessShim,
kxmBackupCeiling,
kxmDeclaredExecutorIds,
kxmDeclaredRepositoryIds,
kxmEventBase,
kxmExecutorPolicyRevision,
kxmIncrementMonotonicNs,
kxmMonotonicNs,
kxmPolicyRevisions,
kxmProjectAdmissionLimits,
kxmProjectRunEventsPath,
kxmRunRevisionDrift,
kxmRuntimePaths,
kxmRuntimeRequest,
kxmSupervisorRecordIsLive,
kxmSupervisorStatus,
kxmSupervisorTokenFile,
kxmToolPolicyRevision,
loadModesConfig,
narrowSubagentTools,
newKxmAssignmentId,
newKxmAttemptId,
newKxmCommandId,
newKxmEffectId,
newKxmEventId,
newKxmEvidenceId,
newKxmObservationId,
newKxmRunId,
oneShotPermissionArgs,
oneShotReadOnlyArgs,
oneShotWriterArgs,
openDatabase,
openKxmRuntimeContext,
parseAgyOneShotUsage,
parseClaudeOneShotUsage,
parseCodexOneShotUsage,
parseGenericOneShotUsage,
parseGrokOneShotUsage,
parseKimiOneShotUsage,
parsePiOneShotUsage,
parseSshConfig,
persistKxmRunState,
planBackup,
planHarnessUpdate,
planRestore,
probeHarnessAssignment,
probeHarnessAssignmentAsync,
probeHarnesses,
probeHarnessesAsync,
probeHarnessesForModel,
probeHarnessesForModelAsync,
projectKxmRunReadOnly,
projectRuntimeKey,
projectRuntimeOwnsRun,
pruneSocketDir,
readKxmRunStatus,
readKxmSupervisorRecord,
readKxmSupervisorToken,
rebuildKxmRunProjection,
redactLogValue,
registerKxmRuntimeCloseHook,
resetLegacySteelAuthWarningForTests,
resolveActiveMode,
resolveBrowserCdpConnect,
resolveBrowserCdpEndpoint,
resolveDispatchStatus,
resolveObscuraCdpEndpoint,
resolvePassCliApiKey,
resolveSshHostG,
resolveSteelAuthorization,
resolveSteelConfig,
resolveViewportDimensions,
restoreBackup,
restoreDatabaseFile,
rotateLogFiles,
runHarnessUpdate,
runtimeError,
runtimeStopGraceMs,
runtimeSyncIntervalMs,
sanitizeLogOutput,
startKxmRuntimeSupervisor,
steelAuthRedirectError,
steelRequestHeaders,
syncKxmOutbox,
tableColumns,
truncateSshOutput,
userTables,
validateHarnessModelPair,
verifyExpectedTables,
verifyKxmDriveReceipt,
withDatabaseTransaction,
writeImprovementReport
};