@ai-matrx/agents 0.20.6 → 0.21.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +18 -1
- package/dist/content-transfer/index.cjs.map +1 -1
- package/dist/content-transfer/index.js.map +1 -1
- package/dist/content-transfer/react/index.cjs.map +1 -1
- package/dist/content-transfer/react/index.js.map +1 -1
- package/dist/context/index.cjs +232 -0
- package/dist/context/index.cjs.map +1 -0
- package/dist/context/index.d.cts +212 -0
- package/dist/context/index.d.ts +212 -0
- package/dist/context/index.js +211 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/react/index.cjs +894 -0
- package/dist/context/react/index.cjs.map +1 -0
- package/dist/context/react/index.d.cts +164 -0
- package/dist/context/react/index.d.ts +164 -0
- package/dist/context/react/index.js +891 -0
- package/dist/context/react/index.js.map +1 -0
- package/dist/mandates/index.cjs +2 -2
- package/dist/mandates/index.cjs.map +1 -1
- package/dist/mandates/index.d.cts +4 -4
- package/dist/mandates/index.d.ts +4 -4
- package/dist/mandates/index.js +2 -2
- package/dist/mandates/index.js.map +1 -1
- package/mandates/snapshots/keys.0.21.1.json +652 -0
- package/mandates/snapshots/keys.0.21.2.json +652 -0
- package/package.json +23 -3
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// context/index.ts
|
|
21
|
+
var context_exports = {};
|
|
22
|
+
__export(context_exports, {
|
|
23
|
+
CONTEXT_RULES_FEATURE: () => CONTEXT_RULES_FEATURE,
|
|
24
|
+
DEFAULT_INLINE_CAP: () => DEFAULT_INLINE_CAP,
|
|
25
|
+
DEFAULT_INLINE_MAX_CHARS: () => DEFAULT_INLINE_MAX_CHARS,
|
|
26
|
+
DEFAULT_SURFACE_KEY: () => DEFAULT_SURFACE_KEY,
|
|
27
|
+
buildContextWire: () => buildContextWire,
|
|
28
|
+
compareReceipt: () => compareReceipt,
|
|
29
|
+
contextValueChars: () => contextValueChars,
|
|
30
|
+
formatChars: () => formatChars,
|
|
31
|
+
lookupSavedRule: () => lookupSavedRule,
|
|
32
|
+
resolveContextRow: () => resolveContextRow,
|
|
33
|
+
resolveContextRule: () => resolveContextRule
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(context_exports);
|
|
36
|
+
var CONTEXT_RULES_FEATURE = "context_rules";
|
|
37
|
+
var DEFAULT_SURFACE_KEY = "_default";
|
|
38
|
+
var DEFAULT_INLINE_MAX_CHARS = 200;
|
|
39
|
+
var DEFAULT_INLINE_CAP = 5e4;
|
|
40
|
+
var isNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
41
|
+
var isValidLimit = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
42
|
+
function resolveContextRule(input) {
|
|
43
|
+
const agent = input.agent ?? null;
|
|
44
|
+
const surface = input.surface ?? null;
|
|
45
|
+
const user = input.user ?? null;
|
|
46
|
+
const cap = isNum(input.cap) ? input.cap : DEFAULT_INLINE_CAP;
|
|
47
|
+
const agentDeclared = agent?.declared === true;
|
|
48
|
+
let include = true;
|
|
49
|
+
let includeBy = "default";
|
|
50
|
+
if (surface?.declared === true && surface.auto_context === false) {
|
|
51
|
+
if (agentDeclared) {
|
|
52
|
+
include = true;
|
|
53
|
+
includeBy = "agent";
|
|
54
|
+
} else {
|
|
55
|
+
include = false;
|
|
56
|
+
includeBy = "page";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (agent?.kill_switch === true && !agentDeclared) {
|
|
60
|
+
include = false;
|
|
61
|
+
includeBy = "agent";
|
|
62
|
+
}
|
|
63
|
+
if (user && typeof user.include === "boolean") {
|
|
64
|
+
include = user.include;
|
|
65
|
+
includeBy = "you";
|
|
66
|
+
}
|
|
67
|
+
let limit = isNum(input.default_max) ? input.default_max : DEFAULT_INLINE_MAX_CHARS;
|
|
68
|
+
let limitBy = "default";
|
|
69
|
+
const a = agentDeclared && isNum(agent?.max_inline_chars) ? agent.max_inline_chars : null;
|
|
70
|
+
const s = isNum(surface?.max_inline_chars) ? surface.max_inline_chars : null;
|
|
71
|
+
if (a !== null && s !== null) {
|
|
72
|
+
if (s < a) {
|
|
73
|
+
limit = s;
|
|
74
|
+
limitBy = "page";
|
|
75
|
+
} else {
|
|
76
|
+
limit = a;
|
|
77
|
+
limitBy = "agent";
|
|
78
|
+
}
|
|
79
|
+
} else if (a !== null) {
|
|
80
|
+
limit = a;
|
|
81
|
+
limitBy = "agent";
|
|
82
|
+
} else if (s !== null) {
|
|
83
|
+
limit = s;
|
|
84
|
+
limitBy = "page";
|
|
85
|
+
}
|
|
86
|
+
if (user && isValidLimit(user.max_inline_chars)) {
|
|
87
|
+
limit = user.max_inline_chars;
|
|
88
|
+
limitBy = "you";
|
|
89
|
+
}
|
|
90
|
+
const clamped = limit > cap;
|
|
91
|
+
limit = Math.min(limit, cap);
|
|
92
|
+
const chars = input.chars;
|
|
93
|
+
const delivery = !include ? "off" : chars === null || chars === void 0 || limit === 0 || chars > limit ? "on_request" : "inline";
|
|
94
|
+
return {
|
|
95
|
+
include,
|
|
96
|
+
max_inline_chars: limit,
|
|
97
|
+
delivery,
|
|
98
|
+
decided_by: { include: includeBy, max_inline_chars: limitBy },
|
|
99
|
+
clamped
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function codePoints(s) {
|
|
103
|
+
let n = 0;
|
|
104
|
+
for (const _ of s) n += 1;
|
|
105
|
+
return n;
|
|
106
|
+
}
|
|
107
|
+
function contextValueChars(value) {
|
|
108
|
+
if (value === void 0) return 0;
|
|
109
|
+
if (typeof value === "string") return codePoints(value);
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
text = JSON.stringify(value, null, 2);
|
|
113
|
+
} catch {
|
|
114
|
+
text = String(value);
|
|
115
|
+
}
|
|
116
|
+
return text === void 0 ? 0 : codePoints(text);
|
|
117
|
+
}
|
|
118
|
+
function sanitizeRule(raw) {
|
|
119
|
+
const out = {};
|
|
120
|
+
if (!raw || typeof raw !== "object") return out;
|
|
121
|
+
const r = raw;
|
|
122
|
+
if (typeof r.include === "boolean") out.include = r.include;
|
|
123
|
+
if (isValidLimit(r.max_inline_chars)) out.max_inline_chars = r.max_inline_chars;
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
function lookupSavedRule(rows, surfaceKey, key) {
|
|
127
|
+
if (!rows || typeof rows !== "object") return null;
|
|
128
|
+
const base = sanitizeRule(rows[DEFAULT_SURFACE_KEY]?.[key]);
|
|
129
|
+
const own = surfaceKey === DEFAULT_SURFACE_KEY ? {} : sanitizeRule(rows[surfaceKey]?.[key]);
|
|
130
|
+
const merged = { ...base, ...own };
|
|
131
|
+
return Object.keys(merged).length === 0 ? null : merged;
|
|
132
|
+
}
|
|
133
|
+
function resolveContextRow(source, savedRows, cap = DEFAULT_INLINE_CAP) {
|
|
134
|
+
const surfaceKey = source.surfaceKey ?? DEFAULT_SURFACE_KEY;
|
|
135
|
+
const chars = source.chars !== void 0 ? source.chars : contextValueChars(envelopeContent(source.value));
|
|
136
|
+
const userRule = lookupSavedRule(savedRows, surfaceKey, source.key);
|
|
137
|
+
const result = resolveContextRule({ ...source.layers ?? {}, chars, user: userRule, cap });
|
|
138
|
+
const row = {
|
|
139
|
+
...result,
|
|
140
|
+
key: source.key,
|
|
141
|
+
label: source.label,
|
|
142
|
+
surfaceKey,
|
|
143
|
+
origin: source.origin,
|
|
144
|
+
value: source.value,
|
|
145
|
+
chars,
|
|
146
|
+
userRule
|
|
147
|
+
};
|
|
148
|
+
if (source.description !== void 0) row.description = source.description;
|
|
149
|
+
if (source.type !== void 0) row.type = source.type;
|
|
150
|
+
if (source.layers !== void 0) row.layers = source.layers;
|
|
151
|
+
return row;
|
|
152
|
+
}
|
|
153
|
+
function isEnvelope(value) {
|
|
154
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "content");
|
|
155
|
+
}
|
|
156
|
+
function envelopeContent(value) {
|
|
157
|
+
return isEnvelope(value) ? value.content : value;
|
|
158
|
+
}
|
|
159
|
+
function buildContextWire(rows) {
|
|
160
|
+
const wire = {};
|
|
161
|
+
for (const row of rows) {
|
|
162
|
+
if (!row.include) continue;
|
|
163
|
+
const rich = isEnvelope(row.value);
|
|
164
|
+
const envelope = rich ? { ...row.value } : { content: row.value };
|
|
165
|
+
delete envelope.max_inline_chars;
|
|
166
|
+
if (envelope.type === void 0 && row.type !== void 0) envelope.type = row.type;
|
|
167
|
+
if (envelope.label === void 0) envelope.label = row.label;
|
|
168
|
+
if (envelope.description === void 0 && row.description !== void 0) {
|
|
169
|
+
envelope.description = row.description;
|
|
170
|
+
}
|
|
171
|
+
const pageLimit = row.layers?.surface?.max_inline_chars;
|
|
172
|
+
const ownPageLimit = rich ? row.value.max_inline_chars : void 0;
|
|
173
|
+
if (isValidLimit(pageLimit)) envelope.max_inline_chars = pageLimit;
|
|
174
|
+
else if (isValidLimit(ownPageLimit)) envelope.max_inline_chars = ownPageLimit;
|
|
175
|
+
wire[row.key] = envelope;
|
|
176
|
+
}
|
|
177
|
+
return wire;
|
|
178
|
+
}
|
|
179
|
+
function normalizeUserRule(rule) {
|
|
180
|
+
const clean = sanitizeRule(rule);
|
|
181
|
+
return Object.keys(clean).length === 0 ? null : clean;
|
|
182
|
+
}
|
|
183
|
+
function sameRule(a, b) {
|
|
184
|
+
if (a === null || b === null) return a === b;
|
|
185
|
+
return a.include === b.include && a.max_inline_chars === b.max_inline_chars;
|
|
186
|
+
}
|
|
187
|
+
function compareReceipt(expected, receipt) {
|
|
188
|
+
const mismatches = [];
|
|
189
|
+
const used = /* @__PURE__ */ new Set();
|
|
190
|
+
const rows = receipt.rows ?? [];
|
|
191
|
+
for (const exp of expected) {
|
|
192
|
+
const actual = rows.find((r) => !used.has(r) && r.key === exp.key && r.surface_key === exp.surfaceKey) ?? rows.find((r) => !used.has(r) && r.key === exp.key);
|
|
193
|
+
if (!actual) {
|
|
194
|
+
const withheldByOthers = !exp.include && exp.decided_by.include !== "you";
|
|
195
|
+
if (!withheldByOthers) {
|
|
196
|
+
mismatches.push({ key: exp.key, field: "missing", expected: exp.delivery, actual: null });
|
|
197
|
+
}
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
used.add(actual);
|
|
201
|
+
if (actual.include !== exp.include) {
|
|
202
|
+
mismatches.push({ key: exp.key, field: "include", expected: exp.include, actual: actual.include });
|
|
203
|
+
}
|
|
204
|
+
if (actual.max_inline_chars !== exp.max_inline_chars) {
|
|
205
|
+
mismatches.push({
|
|
206
|
+
key: exp.key,
|
|
207
|
+
field: "max_inline_chars",
|
|
208
|
+
expected: exp.max_inline_chars,
|
|
209
|
+
actual: actual.max_inline_chars
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
if (exp.chars !== null && actual.chars !== null && actual.delivery !== exp.delivery) {
|
|
213
|
+
mismatches.push({ key: exp.key, field: "delivery", expected: exp.delivery, actual: actual.delivery });
|
|
214
|
+
}
|
|
215
|
+
const expRule = normalizeUserRule(exp.userRule);
|
|
216
|
+
const actRule = normalizeUserRule(actual.user_rule);
|
|
217
|
+
if (!sameRule(expRule, actRule)) {
|
|
218
|
+
mismatches.push({ key: exp.key, field: "user_rule", expected: expRule, actual: actRule });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { mismatches, systemRows: rows.filter((r) => !used.has(r)) };
|
|
222
|
+
}
|
|
223
|
+
function formatChars(n) {
|
|
224
|
+
if (n === null || n === void 0 || !Number.isFinite(n)) return "\u2014";
|
|
225
|
+
const abs = Math.abs(n);
|
|
226
|
+
const trim = (s) => s.replace(/\.0$/, "");
|
|
227
|
+
if (abs < 1e3) return String(Math.round(n));
|
|
228
|
+
if (abs < 1e5) return `${trim((n / 1e3).toFixed(1))}k`;
|
|
229
|
+
if (abs < 1e6) return `${Math.round(n / 1e3)}k`;
|
|
230
|
+
return `${trim((n / 1e6).toFixed(1))}M`;
|
|
231
|
+
}
|
|
232
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../context/index.ts"],"sourcesContent":["/**\n * @ai-matrx/agents/context — the context value rules, headless.\n *\n * Contract: common-docs/systems/scopes-context/context-delivery/RULES.md.\n * Parity corpus: ./rules-corpus.json (run here by rules.test.ts and by aidream's\n * pytest against the Python twin `resolve_context_rule`). Every function here\n * is pure, zero-React, and safe to import on a server.\n *\n * The one flow a client runs per turn:\n * rows = values.map(v => resolveContextRow(v, savedRows, cap)) // what the table shows\n * context = buildContextWire(rows) // what the request sends\n * …on `context_receipt`: compareReceipt(rows, receipt) // screen vs server\n */\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/** `users.user_surface_state.feature` for the person's saved rules. */\nexport const CONTEXT_RULES_FEATURE = \"context_rules\";\n/** Surface key for values no surface emitted (attachments, server-added values). */\nexport const DEFAULT_SURFACE_KEY = \"_default\";\n/** The server's default inline threshold when no layer sets one. */\nexport const DEFAULT_INLINE_MAX_CHARS = 200;\n/** The default ceiling every resolved limit is clamped to (a server knob). */\nexport const DEFAULT_INLINE_CAP = 50000;\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** Which layer decided a field — lowest to highest. */\nexport type ContextLayer = \"default\" | \"page\" | \"agent\" | \"you\";\nexport type ContextDelivery = \"inline\" | \"on_request\" | \"off\";\n\n/** One saved per-person rule (one key on one surface). Both fields optional. */\nexport interface SavedContextRule {\n include?: boolean;\n max_inline_chars?: number;\n}\n\n/** `{ [surface_key]: { [context key]: SavedContextRule } }` — the person's rows. */\nexport type SavedContextRuleRows = Record<string, Record<string, SavedContextRule>>;\n\n/** The agent layer for one key (RULES.md §2). */\nexport interface ContextAgentLayer {\n /** The agent's Context Policy declares this key (or the value is the agent's own seed). */\n declared?: boolean;\n /** The policy's ceiling; only read when `declared`. */\n max_inline_chars?: number | null;\n /** `auto_context_disabled` — closes every undeclared key. */\n kill_switch?: boolean;\n}\n\n/** The page layer for one key: the surface that emitted the value. */\nexport interface ContextSurfaceLayer {\n /** The surface declares this value (a `ui_surface_value` row / manifest entry). */\n declared?: boolean;\n /** `false` drops the value unless the agent declares it. */\n auto_context?: boolean | null;\n /** `inlineUpTo` / envelope `max_inline_chars` / DB column. */\n max_inline_chars?: number | null;\n}\n\n/** The non-person layers for one value — what the table's layer breakdown shows. */\nexport interface ContextRuleLayers {\n /** The server's per-key default limit; `null`/absent = 200. */\n default_max?: number | null;\n agent?: ContextAgentLayer | null;\n surface?: ContextSurfaceLayer | null;\n}\n\n/**\n * Input to `resolveContextRule`. Snake case on purpose: it is the corpus shape\n * and the Python twin's shape. `user` is typed loosely because invalid saved\n * values (non-boolean include, non-integer or negative limit) must be ignored,\n * not trusted.\n */\nexport interface ContextRuleInput extends ContextRuleLayers {\n /** Size in code points; `null` = an unresolved lazy source. */\n chars: number | null;\n user?: { include?: unknown; max_inline_chars?: unknown } | null;\n /** Ceiling; default `DEFAULT_INLINE_CAP`. */\n cap?: number;\n}\n\nexport interface ContextRuleResult {\n include: boolean;\n /** Effective limit, after the clamp. */\n max_inline_chars: number;\n delivery: ContextDelivery;\n decided_by: { include: ContextLayer; max_inline_chars: ContextLayer };\n clamped: boolean;\n}\n\n/** One receipt row — RULES.md §5, wire fields exactly. */\nexport interface ContextReceiptRow {\n key: string;\n label: string;\n surface_key: string;\n origin: \"client\" | \"server\" | \"surroundings\" | \"rule\";\n chars: number | null;\n include: boolean;\n max_inline_chars: number;\n delivery: ContextDelivery;\n decided_by: { include: ContextLayer; max_inline_chars: ContextLayer };\n user_rule: { include?: boolean; max_inline_chars?: number } | null;\n clamped: boolean;\n /** The CLIENT itself sent a value the person turned off. */\n client_sent_excluded: boolean;\n /** `\"model\"`: nothing reached a model that reads no context. */\n blocked_by: \"model\" | null;\n}\n\n/** The per-turn receipt the server streams as `context_receipt` — RULES.md §5. */\nexport interface ContextReceipt {\n version: 1;\n surface: string | null;\n cap: number;\n /** False: this turn's model cannot read context at all (every row `blocked_by: \"model\"`). */\n model_reads_context: boolean;\n /** The person's saved rules could not be read; the turn ran without them. */\n rules_error: string | null;\n rows: ContextReceiptRow[];\n}\n\nexport type ContextRowOrigin = \"page\" | \"attached\" | \"system\";\n\n/** A client's resolved row: what its table renders and what `buildContextWire` sends. */\nexport interface ResolvedContextRow extends ContextRuleResult {\n key: string;\n label: string;\n surfaceKey: string;\n origin: ContextRowOrigin;\n /** The raw value, or an already-rich envelope (`{ content, type, … }`). */\n value: unknown;\n chars: number | null;\n /** The saved rule that was applied (merged `_default` + surface row), or null. */\n userRule: SavedContextRule | null;\n description?: string;\n /** Context object type for the wire envelope (`text`, `json`, …). */\n type?: string;\n /** The non-person layers the rule was resolved from. Absent = default only. */\n layers?: ContextRuleLayers;\n}\n\n/** What a client knows about one value before resolution. */\nexport interface ContextRowSource {\n key: string;\n label: string;\n surfaceKey?: string;\n origin: ContextRowOrigin;\n value: unknown;\n /** Override the measured size (e.g. `null` for an unresolved lazy source). */\n chars?: number | null;\n description?: string;\n type?: string;\n layers?: ContextRuleLayers;\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nconst isNum = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v);\nconst isValidLimit = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isInteger(v) && v >= 0;\n\n// ── resolveContextRule — RULES.md §2, line for line ─────────────────────────\n\nexport function resolveContextRule(input: ContextRuleInput): ContextRuleResult {\n const agent = input.agent ?? null;\n const surface = input.surface ?? null;\n const user = input.user ?? null;\n const cap = isNum(input.cap) ? input.cap : DEFAULT_INLINE_CAP;\n const agentDeclared = agent?.declared === true;\n\n let include = true;\n let includeBy: ContextLayer = \"default\";\n if (surface?.declared === true && surface.auto_context === false) {\n if (agentDeclared) {\n include = true;\n includeBy = \"agent\";\n } else {\n include = false;\n includeBy = \"page\";\n }\n }\n if (agent?.kill_switch === true && !agentDeclared) {\n include = false;\n includeBy = \"agent\";\n }\n if (user && typeof user.include === \"boolean\") {\n include = user.include;\n includeBy = \"you\";\n }\n\n let limit = isNum(input.default_max) ? input.default_max : DEFAULT_INLINE_MAX_CHARS;\n let limitBy: ContextLayer = \"default\";\n const a = agentDeclared && isNum(agent?.max_inline_chars) ? agent.max_inline_chars : null;\n const s = isNum(surface?.max_inline_chars) ? surface.max_inline_chars : null;\n if (a !== null && s !== null) {\n if (s < a) {\n limit = s;\n limitBy = \"page\";\n } else {\n limit = a;\n limitBy = \"agent\";\n }\n } else if (a !== null) {\n limit = a;\n limitBy = \"agent\";\n } else if (s !== null) {\n limit = s;\n limitBy = \"page\";\n }\n if (user && isValidLimit(user.max_inline_chars)) {\n limit = user.max_inline_chars;\n limitBy = \"you\";\n }\n const clamped = limit > cap;\n limit = Math.min(limit, cap);\n\n const chars = input.chars;\n const delivery: ContextDelivery = !include\n ? \"off\"\n : chars === null || chars === undefined || limit === 0 || chars > limit\n ? \"on_request\"\n : \"inline\";\n\n return {\n include,\n max_inline_chars: limit,\n delivery,\n decided_by: { include: includeBy, max_inline_chars: limitBy },\n clamped,\n };\n}\n\n// ── contextValueChars — RULES.md §1 ─────────────────────────────────────────\n\n/** Count Unicode code points (never UTF-16 units: `\"😀\".length` is 2). */\nfunction codePoints(s: string): number {\n let n = 0;\n for (const _ of s) n += 1;\n return n;\n}\n\n/**\n * Size of a value in code points, exactly as the server's `content_as_str()`:\n * a string is itself; anything else is `JSON.stringify(value, null, 2)`\n * (Python `json.dumps(value, ensure_ascii=False, indent=2)`). `undefined` → 0.\n */\nexport function contextValueChars(value: unknown): number {\n if (value === undefined) return 0;\n if (typeof value === \"string\") return codePoints(value);\n let text: string | undefined;\n try {\n text = JSON.stringify(value, null, 2);\n } catch {\n text = String(value);\n }\n return text === undefined ? 0 : codePoints(text);\n}\n\n// ── lookupSavedRule — RULES.md §3 ───────────────────────────────────────────\n\nfunction sanitizeRule(raw: unknown): SavedContextRule {\n const out: SavedContextRule = {};\n if (!raw || typeof raw !== \"object\") return out;\n const r = raw as Record<string, unknown>;\n if (typeof r.include === \"boolean\") out.include = r.include;\n if (isValidLimit(r.max_inline_chars)) out.max_inline_chars = r.max_inline_chars;\n return out;\n}\n\n/**\n * The person's rule for one key on one surface: `_default[key]` merged per\n * field under `rows[surfaceKey][key]`, invalid fields stripped. `null` when\n * nothing valid is saved.\n */\nexport function lookupSavedRule(\n rows: SavedContextRuleRows | null | undefined,\n surfaceKey: string,\n key: string,\n): SavedContextRule | null {\n if (!rows || typeof rows !== \"object\") return null;\n const base = sanitizeRule(rows[DEFAULT_SURFACE_KEY]?.[key]);\n const own = surfaceKey === DEFAULT_SURFACE_KEY ? {} : sanitizeRule(rows[surfaceKey]?.[key]);\n const merged: SavedContextRule = { ...base, ...own };\n return Object.keys(merged).length === 0 ? null : merged;\n}\n\n// ── resolveContextRow — the glue a client runs per value ────────────────────\n\n/** Resolve one value into the row the table renders and the wire sends. */\nexport function resolveContextRow(\n source: ContextRowSource,\n savedRows: SavedContextRuleRows | null | undefined,\n cap: number = DEFAULT_INLINE_CAP,\n): ResolvedContextRow {\n const surfaceKey = source.surfaceKey ?? DEFAULT_SURFACE_KEY;\n const chars =\n source.chars !== undefined ? source.chars : contextValueChars(envelopeContent(source.value));\n const userRule = lookupSavedRule(savedRows, surfaceKey, source.key);\n const result = resolveContextRule({ ...(source.layers ?? {}), chars, user: userRule, cap });\n const row: ResolvedContextRow = {\n ...result,\n key: source.key,\n label: source.label,\n surfaceKey,\n origin: source.origin,\n value: source.value,\n chars,\n userRule,\n };\n if (source.description !== undefined) row.description = source.description;\n if (source.type !== undefined) row.type = source.type;\n if (source.layers !== undefined) row.layers = source.layers;\n return row;\n}\n\n// ── buildContextWire — the ONLY producer of a request's `context` ──────────\n\nfunction isEnvelope(value: unknown): value is Record<string, unknown> {\n return (\n !!value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.prototype.hasOwnProperty.call(value, \"content\")\n );\n}\n\nfunction envelopeContent(value: unknown): unknown {\n return isEnvelope(value) ? value.content : value;\n}\n\n/**\n * Build the request's `context` object from the resolved rows. This is the\n * ONLY function that may produce it, so what the table shows and what the\n * request carries cannot drift apart.\n *\n * - A row whose `include` is false is omitted entirely — it never reaches the\n * wire (RULES.md §1: off means off everywhere).\n * - An included row becomes `{ content, type?, label, description?,\n * max_inline_chars? }`. An already-rich envelope (a value with its own\n * `content`, e.g. a working document carrying `source`/`mutable`/`persist`)\n * keeps every non-rule field it already has; `label`/`description`/`type`\n * are only filled when missing.\n * - `max_inline_chars` on the envelope is the PAGE layer's value only\n * (`layers.surface.max_inline_chars`, else the envelope's own page value).\n * The server reads the person's saved rules itself every turn (RULES.md §3)\n * and the agent layer from its own policy, so the wire must never carry the\n * person's number or the resolved effective limit dressed up as a page rule\n * — that would make a stale client value outrank the server's fresh read.\n */\nexport function buildContextWire(rows: readonly ResolvedContextRow[]): Record<string, unknown> {\n const wire: Record<string, unknown> = {};\n for (const row of rows) {\n if (!row.include) continue;\n const rich = isEnvelope(row.value);\n const envelope: Record<string, unknown> = rich\n ? { ...(row.value as Record<string, unknown>) }\n : { content: row.value };\n delete envelope.max_inline_chars;\n if (envelope.type === undefined && row.type !== undefined) envelope.type = row.type;\n if (envelope.label === undefined) envelope.label = row.label;\n if (envelope.description === undefined && row.description !== undefined) {\n envelope.description = row.description;\n }\n const pageLimit = row.layers?.surface?.max_inline_chars;\n const ownPageLimit = rich ? (row.value as Record<string, unknown>).max_inline_chars : undefined;\n if (isValidLimit(pageLimit)) envelope.max_inline_chars = pageLimit;\n else if (isValidLimit(ownPageLimit)) envelope.max_inline_chars = ownPageLimit;\n wire[row.key] = envelope;\n }\n return wire;\n}\n\n// ── compareReceipt — RULES.md §6 ────────────────────────────────────────────\n\nexport interface ContextReceiptMismatch {\n key: string;\n field: \"include\" | \"max_inline_chars\" | \"delivery\" | \"user_rule\" | \"missing\";\n expected: unknown;\n actual: unknown;\n}\n\nfunction normalizeUserRule(rule: SavedContextRule | null | undefined): SavedContextRule | null {\n const clean = sanitizeRule(rule);\n return Object.keys(clean).length === 0 ? null : clean;\n}\n\nfunction sameRule(a: SavedContextRule | null, b: SavedContextRule | null): boolean {\n if (a === null || b === null) return a === b;\n return a.include === b.include && a.max_inline_chars === b.max_inline_chars;\n}\n\n/**\n * Compare the rows the client resolved (and rendered, and sent) with the\n * receipt the server emitted for the same turn.\n *\n * For each expected row, the receipt row is matched by key + surface key, then\n * by key alone. Compared: `include`, `max_inline_chars`, `delivery` (only when\n * both sides know the size) and `user_rule`. An expected row absent from the\n * receipt is a `missing` mismatch — except a row the client correctly withheld\n * for a reason other than the person's own rule (page `auto_context` off, the\n * agent's kill switch): the client never sent it and the server lists only\n * the person's saved `include: false` rules as `origin: \"rule\"` rows, so its\n * absence is the truth, not a lie. Receipt rows nobody expected are returned\n * as `systemRows` — shown, never hidden.\n */\nexport function compareReceipt(\n expected: readonly ResolvedContextRow[],\n receipt: ContextReceipt,\n): { mismatches: ContextReceiptMismatch[]; systemRows: ContextReceiptRow[] } {\n const mismatches: ContextReceiptMismatch[] = [];\n const used = new Set<ContextReceiptRow>();\n const rows = receipt.rows ?? [];\n\n for (const exp of expected) {\n const actual =\n rows.find((r) => !used.has(r) && r.key === exp.key && r.surface_key === exp.surfaceKey) ??\n rows.find((r) => !used.has(r) && r.key === exp.key);\n if (!actual) {\n const withheldByOthers = !exp.include && exp.decided_by.include !== \"you\";\n if (!withheldByOthers) {\n mismatches.push({ key: exp.key, field: \"missing\", expected: exp.delivery, actual: null });\n }\n continue;\n }\n used.add(actual);\n if (actual.include !== exp.include) {\n mismatches.push({ key: exp.key, field: \"include\", expected: exp.include, actual: actual.include });\n }\n if (actual.max_inline_chars !== exp.max_inline_chars) {\n mismatches.push({\n key: exp.key,\n field: \"max_inline_chars\",\n expected: exp.max_inline_chars,\n actual: actual.max_inline_chars,\n });\n }\n if (exp.chars !== null && actual.chars !== null && actual.delivery !== exp.delivery) {\n mismatches.push({ key: exp.key, field: \"delivery\", expected: exp.delivery, actual: actual.delivery });\n }\n const expRule = normalizeUserRule(exp.userRule);\n const actRule = normalizeUserRule(actual.user_rule);\n if (!sameRule(expRule, actRule)) {\n mismatches.push({ key: exp.key, field: \"user_rule\", expected: expRule, actual: actRule });\n }\n }\n\n return { mismatches, systemRows: rows.filter((r) => !used.has(r)) };\n}\n\n// ── Display ─────────────────────────────────────────────────────────────────\n\n/** Compact size for a tabular column: `950`, `18.4k`, `184k`, `1.2M`, `—` for unknown. */\nexport function formatChars(n: number | null | undefined): string {\n if (n === null || n === undefined || !Number.isFinite(n)) return \"—\";\n const abs = Math.abs(n);\n const trim = (s: string) => s.replace(/\\.0$/, \"\");\n if (abs < 1000) return String(Math.round(n));\n if (abs < 100_000) return `${trim((n / 1000).toFixed(1))}k`;\n if (abs < 1_000_000) return `${Math.round(n / 1000)}k`;\n return `${trim((n / 1_000_000).toFixed(1))}M`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,IAAS,QAAO,GAAG,MAAM,IAAI,KAAM,QAAQ,CAAC,CAAC,CAAC;AACxD,MAAI,MAAM,IAAW,QAAO,GAAG,KAAK,MAAM,IAAI,GAAI,CAAC;AACnD,SAAO,GAAG,MAAM,IAAI,KAAW,QAAQ,CAAC,CAAC,CAAC;AAC5C;","names":[]}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @ai-matrx/agents/context — the context value rules, headless.
|
|
3
|
+
*
|
|
4
|
+
* Contract: common-docs/systems/scopes-context/context-delivery/RULES.md.
|
|
5
|
+
* Parity corpus: ./rules-corpus.json (run here by rules.test.ts and by aidream's
|
|
6
|
+
* pytest against the Python twin `resolve_context_rule`). Every function here
|
|
7
|
+
* is pure, zero-React, and safe to import on a server.
|
|
8
|
+
*
|
|
9
|
+
* The one flow a client runs per turn:
|
|
10
|
+
* rows = values.map(v => resolveContextRow(v, savedRows, cap)) // what the table shows
|
|
11
|
+
* context = buildContextWire(rows) // what the request sends
|
|
12
|
+
* …on `context_receipt`: compareReceipt(rows, receipt) // screen vs server
|
|
13
|
+
*/
|
|
14
|
+
/** `users.user_surface_state.feature` for the person's saved rules. */
|
|
15
|
+
declare const CONTEXT_RULES_FEATURE = "context_rules";
|
|
16
|
+
/** Surface key for values no surface emitted (attachments, server-added values). */
|
|
17
|
+
declare const DEFAULT_SURFACE_KEY = "_default";
|
|
18
|
+
/** The server's default inline threshold when no layer sets one. */
|
|
19
|
+
declare const DEFAULT_INLINE_MAX_CHARS = 200;
|
|
20
|
+
/** The default ceiling every resolved limit is clamped to (a server knob). */
|
|
21
|
+
declare const DEFAULT_INLINE_CAP = 50000;
|
|
22
|
+
/** Which layer decided a field — lowest to highest. */
|
|
23
|
+
type ContextLayer = "default" | "page" | "agent" | "you";
|
|
24
|
+
type ContextDelivery = "inline" | "on_request" | "off";
|
|
25
|
+
/** One saved per-person rule (one key on one surface). Both fields optional. */
|
|
26
|
+
interface SavedContextRule {
|
|
27
|
+
include?: boolean;
|
|
28
|
+
max_inline_chars?: number;
|
|
29
|
+
}
|
|
30
|
+
/** `{ [surface_key]: { [context key]: SavedContextRule } }` — the person's rows. */
|
|
31
|
+
type SavedContextRuleRows = Record<string, Record<string, SavedContextRule>>;
|
|
32
|
+
/** The agent layer for one key (RULES.md §2). */
|
|
33
|
+
interface ContextAgentLayer {
|
|
34
|
+
/** The agent's Context Policy declares this key (or the value is the agent's own seed). */
|
|
35
|
+
declared?: boolean;
|
|
36
|
+
/** The policy's ceiling; only read when `declared`. */
|
|
37
|
+
max_inline_chars?: number | null;
|
|
38
|
+
/** `auto_context_disabled` — closes every undeclared key. */
|
|
39
|
+
kill_switch?: boolean;
|
|
40
|
+
}
|
|
41
|
+
/** The page layer for one key: the surface that emitted the value. */
|
|
42
|
+
interface ContextSurfaceLayer {
|
|
43
|
+
/** The surface declares this value (a `ui_surface_value` row / manifest entry). */
|
|
44
|
+
declared?: boolean;
|
|
45
|
+
/** `false` drops the value unless the agent declares it. */
|
|
46
|
+
auto_context?: boolean | null;
|
|
47
|
+
/** `inlineUpTo` / envelope `max_inline_chars` / DB column. */
|
|
48
|
+
max_inline_chars?: number | null;
|
|
49
|
+
}
|
|
50
|
+
/** The non-person layers for one value — what the table's layer breakdown shows. */
|
|
51
|
+
interface ContextRuleLayers {
|
|
52
|
+
/** The server's per-key default limit; `null`/absent = 200. */
|
|
53
|
+
default_max?: number | null;
|
|
54
|
+
agent?: ContextAgentLayer | null;
|
|
55
|
+
surface?: ContextSurfaceLayer | null;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Input to `resolveContextRule`. Snake case on purpose: it is the corpus shape
|
|
59
|
+
* and the Python twin's shape. `user` is typed loosely because invalid saved
|
|
60
|
+
* values (non-boolean include, non-integer or negative limit) must be ignored,
|
|
61
|
+
* not trusted.
|
|
62
|
+
*/
|
|
63
|
+
interface ContextRuleInput extends ContextRuleLayers {
|
|
64
|
+
/** Size in code points; `null` = an unresolved lazy source. */
|
|
65
|
+
chars: number | null;
|
|
66
|
+
user?: {
|
|
67
|
+
include?: unknown;
|
|
68
|
+
max_inline_chars?: unknown;
|
|
69
|
+
} | null;
|
|
70
|
+
/** Ceiling; default `DEFAULT_INLINE_CAP`. */
|
|
71
|
+
cap?: number;
|
|
72
|
+
}
|
|
73
|
+
interface ContextRuleResult {
|
|
74
|
+
include: boolean;
|
|
75
|
+
/** Effective limit, after the clamp. */
|
|
76
|
+
max_inline_chars: number;
|
|
77
|
+
delivery: ContextDelivery;
|
|
78
|
+
decided_by: {
|
|
79
|
+
include: ContextLayer;
|
|
80
|
+
max_inline_chars: ContextLayer;
|
|
81
|
+
};
|
|
82
|
+
clamped: boolean;
|
|
83
|
+
}
|
|
84
|
+
/** One receipt row — RULES.md §5, wire fields exactly. */
|
|
85
|
+
interface ContextReceiptRow {
|
|
86
|
+
key: string;
|
|
87
|
+
label: string;
|
|
88
|
+
surface_key: string;
|
|
89
|
+
origin: "client" | "server" | "surroundings" | "rule";
|
|
90
|
+
chars: number | null;
|
|
91
|
+
include: boolean;
|
|
92
|
+
max_inline_chars: number;
|
|
93
|
+
delivery: ContextDelivery;
|
|
94
|
+
decided_by: {
|
|
95
|
+
include: ContextLayer;
|
|
96
|
+
max_inline_chars: ContextLayer;
|
|
97
|
+
};
|
|
98
|
+
user_rule: {
|
|
99
|
+
include?: boolean;
|
|
100
|
+
max_inline_chars?: number;
|
|
101
|
+
} | null;
|
|
102
|
+
clamped: boolean;
|
|
103
|
+
/** The CLIENT itself sent a value the person turned off. */
|
|
104
|
+
client_sent_excluded: boolean;
|
|
105
|
+
/** `"model"`: nothing reached a model that reads no context. */
|
|
106
|
+
blocked_by: "model" | null;
|
|
107
|
+
}
|
|
108
|
+
/** The per-turn receipt the server streams as `context_receipt` — RULES.md §5. */
|
|
109
|
+
interface ContextReceipt {
|
|
110
|
+
version: 1;
|
|
111
|
+
surface: string | null;
|
|
112
|
+
cap: number;
|
|
113
|
+
/** False: this turn's model cannot read context at all (every row `blocked_by: "model"`). */
|
|
114
|
+
model_reads_context: boolean;
|
|
115
|
+
/** The person's saved rules could not be read; the turn ran without them. */
|
|
116
|
+
rules_error: string | null;
|
|
117
|
+
rows: ContextReceiptRow[];
|
|
118
|
+
}
|
|
119
|
+
type ContextRowOrigin = "page" | "attached" | "system";
|
|
120
|
+
/** A client's resolved row: what its table renders and what `buildContextWire` sends. */
|
|
121
|
+
interface ResolvedContextRow extends ContextRuleResult {
|
|
122
|
+
key: string;
|
|
123
|
+
label: string;
|
|
124
|
+
surfaceKey: string;
|
|
125
|
+
origin: ContextRowOrigin;
|
|
126
|
+
/** The raw value, or an already-rich envelope (`{ content, type, … }`). */
|
|
127
|
+
value: unknown;
|
|
128
|
+
chars: number | null;
|
|
129
|
+
/** The saved rule that was applied (merged `_default` + surface row), or null. */
|
|
130
|
+
userRule: SavedContextRule | null;
|
|
131
|
+
description?: string;
|
|
132
|
+
/** Context object type for the wire envelope (`text`, `json`, …). */
|
|
133
|
+
type?: string;
|
|
134
|
+
/** The non-person layers the rule was resolved from. Absent = default only. */
|
|
135
|
+
layers?: ContextRuleLayers;
|
|
136
|
+
}
|
|
137
|
+
/** What a client knows about one value before resolution. */
|
|
138
|
+
interface ContextRowSource {
|
|
139
|
+
key: string;
|
|
140
|
+
label: string;
|
|
141
|
+
surfaceKey?: string;
|
|
142
|
+
origin: ContextRowOrigin;
|
|
143
|
+
value: unknown;
|
|
144
|
+
/** Override the measured size (e.g. `null` for an unresolved lazy source). */
|
|
145
|
+
chars?: number | null;
|
|
146
|
+
description?: string;
|
|
147
|
+
type?: string;
|
|
148
|
+
layers?: ContextRuleLayers;
|
|
149
|
+
}
|
|
150
|
+
declare function resolveContextRule(input: ContextRuleInput): ContextRuleResult;
|
|
151
|
+
/**
|
|
152
|
+
* Size of a value in code points, exactly as the server's `content_as_str()`:
|
|
153
|
+
* a string is itself; anything else is `JSON.stringify(value, null, 2)`
|
|
154
|
+
* (Python `json.dumps(value, ensure_ascii=False, indent=2)`). `undefined` → 0.
|
|
155
|
+
*/
|
|
156
|
+
declare function contextValueChars(value: unknown): number;
|
|
157
|
+
/**
|
|
158
|
+
* The person's rule for one key on one surface: `_default[key]` merged per
|
|
159
|
+
* field under `rows[surfaceKey][key]`, invalid fields stripped. `null` when
|
|
160
|
+
* nothing valid is saved.
|
|
161
|
+
*/
|
|
162
|
+
declare function lookupSavedRule(rows: SavedContextRuleRows | null | undefined, surfaceKey: string, key: string): SavedContextRule | null;
|
|
163
|
+
/** Resolve one value into the row the table renders and the wire sends. */
|
|
164
|
+
declare function resolveContextRow(source: ContextRowSource, savedRows: SavedContextRuleRows | null | undefined, cap?: number): ResolvedContextRow;
|
|
165
|
+
/**
|
|
166
|
+
* Build the request's `context` object from the resolved rows. This is the
|
|
167
|
+
* ONLY function that may produce it, so what the table shows and what the
|
|
168
|
+
* request carries cannot drift apart.
|
|
169
|
+
*
|
|
170
|
+
* - A row whose `include` is false is omitted entirely — it never reaches the
|
|
171
|
+
* wire (RULES.md §1: off means off everywhere).
|
|
172
|
+
* - An included row becomes `{ content, type?, label, description?,
|
|
173
|
+
* max_inline_chars? }`. An already-rich envelope (a value with its own
|
|
174
|
+
* `content`, e.g. a working document carrying `source`/`mutable`/`persist`)
|
|
175
|
+
* keeps every non-rule field it already has; `label`/`description`/`type`
|
|
176
|
+
* are only filled when missing.
|
|
177
|
+
* - `max_inline_chars` on the envelope is the PAGE layer's value only
|
|
178
|
+
* (`layers.surface.max_inline_chars`, else the envelope's own page value).
|
|
179
|
+
* The server reads the person's saved rules itself every turn (RULES.md §3)
|
|
180
|
+
* and the agent layer from its own policy, so the wire must never carry the
|
|
181
|
+
* person's number or the resolved effective limit dressed up as a page rule
|
|
182
|
+
* — that would make a stale client value outrank the server's fresh read.
|
|
183
|
+
*/
|
|
184
|
+
declare function buildContextWire(rows: readonly ResolvedContextRow[]): Record<string, unknown>;
|
|
185
|
+
interface ContextReceiptMismatch {
|
|
186
|
+
key: string;
|
|
187
|
+
field: "include" | "max_inline_chars" | "delivery" | "user_rule" | "missing";
|
|
188
|
+
expected: unknown;
|
|
189
|
+
actual: unknown;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Compare the rows the client resolved (and rendered, and sent) with the
|
|
193
|
+
* receipt the server emitted for the same turn.
|
|
194
|
+
*
|
|
195
|
+
* For each expected row, the receipt row is matched by key + surface key, then
|
|
196
|
+
* by key alone. Compared: `include`, `max_inline_chars`, `delivery` (only when
|
|
197
|
+
* both sides know the size) and `user_rule`. An expected row absent from the
|
|
198
|
+
* receipt is a `missing` mismatch — except a row the client correctly withheld
|
|
199
|
+
* for a reason other than the person's own rule (page `auto_context` off, the
|
|
200
|
+
* agent's kill switch): the client never sent it and the server lists only
|
|
201
|
+
* the person's saved `include: false` rules as `origin: "rule"` rows, so its
|
|
202
|
+
* absence is the truth, not a lie. Receipt rows nobody expected are returned
|
|
203
|
+
* as `systemRows` — shown, never hidden.
|
|
204
|
+
*/
|
|
205
|
+
declare function compareReceipt(expected: readonly ResolvedContextRow[], receipt: ContextReceipt): {
|
|
206
|
+
mismatches: ContextReceiptMismatch[];
|
|
207
|
+
systemRows: ContextReceiptRow[];
|
|
208
|
+
};
|
|
209
|
+
/** Compact size for a tabular column: `950`, `18.4k`, `184k`, `1.2M`, `—` for unknown. */
|
|
210
|
+
declare function formatChars(n: number | null | undefined): string;
|
|
211
|
+
|
|
212
|
+
export { CONTEXT_RULES_FEATURE, type ContextAgentLayer, type ContextDelivery, type ContextLayer, type ContextReceipt, type ContextReceiptMismatch, type ContextReceiptRow, type ContextRowOrigin, type ContextRowSource, type ContextRuleInput, type ContextRuleLayers, type ContextRuleResult, type ContextSurfaceLayer, DEFAULT_INLINE_CAP, DEFAULT_INLINE_MAX_CHARS, DEFAULT_SURFACE_KEY, type ResolvedContextRow, type SavedContextRule, type SavedContextRuleRows, buildContextWire, compareReceipt, contextValueChars, formatChars, lookupSavedRule, resolveContextRow, resolveContextRule };
|