@orangecheck/agent-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scope.mjs ADDED
@@ -0,0 +1,241 @@
1
+ // src/scope.ts
2
+ var REGISTERED_SCOPES = {
3
+ "lock:seal": { keys: ["recipient", "mime", "max_bytes"] },
4
+ "lock:chat": { keys: ["recipient", "max_bytes_per_msg", "max_msgs"] },
5
+ "stamp:sign": { keys: ["mime", "max_bytes", "content_hash_prefix"] },
6
+ "vote:cast": { keys: ["poll_id", "choice"] },
7
+ "nostr:publish": { keys: ["kind", "relay", "max_bytes"] },
8
+ "http:request": { keys: ["origin", "method", "max_rps", "max_bytes_out"] },
9
+ "ln:send": { keys: ["max_sats", "node", "max_fee_sats"] },
10
+ "mcp:invoke": { keys: ["server", "tool", "max_invocations"] }
11
+ };
12
+ var NUMERIC_KEYS = /* @__PURE__ */ new Set([
13
+ "max_bytes",
14
+ "max_bytes_per_msg",
15
+ "max_msgs",
16
+ "max_bytes_out",
17
+ "max_rps",
18
+ "max_sats",
19
+ "max_fee_sats",
20
+ "max_invocations",
21
+ "kind"
22
+ ]);
23
+ var IDENT_RE = /^[a-z][a-z0-9_]*$/;
24
+ var BARE_TOKEN_RE = /^[A-Za-z0-9_.:/@+\-]+$/;
25
+ var ScopeParseError = class extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = "ScopeParseError";
29
+ }
30
+ };
31
+ function parseScope(input) {
32
+ if (typeof input !== "string" || input.length === 0) {
33
+ throw new ScopeParseError("scope must be a non-empty string");
34
+ }
35
+ if (/\s/.test(input)) {
36
+ throw new ScopeParseError(`scope may not contain whitespace: ${JSON.stringify(input)}`);
37
+ }
38
+ const colonIdx = input.indexOf(":");
39
+ if (colonIdx < 0) throw new ScopeParseError('scope missing "product:verb" separator');
40
+ const product = input.slice(0, colonIdx);
41
+ if (!IDENT_RE.test(product)) throw new ScopeParseError(`invalid product: ${product}`);
42
+ const rest = input.slice(colonIdx + 1);
43
+ const parenIdx = rest.indexOf("(");
44
+ let verb;
45
+ let constraintText = "";
46
+ if (parenIdx < 0) {
47
+ verb = rest;
48
+ } else {
49
+ verb = rest.slice(0, parenIdx);
50
+ if (!rest.endsWith(")")) throw new ScopeParseError('scope constraint list must end with ")"');
51
+ constraintText = rest.slice(parenIdx + 1, -1);
52
+ }
53
+ if (!IDENT_RE.test(verb)) throw new ScopeParseError(`invalid verb: ${verb}`);
54
+ const constraints = [];
55
+ if (constraintText.length > 0) {
56
+ for (const piece of splitTopLevelCommas(constraintText)) {
57
+ constraints.push(parseConstraint(piece));
58
+ }
59
+ }
60
+ const seen = /* @__PURE__ */ new Set();
61
+ for (const c of constraints) {
62
+ if (seen.has(c.key)) throw new ScopeParseError(`duplicate constraint key: ${c.key}`);
63
+ seen.add(c.key);
64
+ }
65
+ return { product, verb, constraints };
66
+ }
67
+ function splitTopLevelCommas(text) {
68
+ const out = [];
69
+ let depth = 0;
70
+ let inQuotes = false;
71
+ let start = 0;
72
+ for (let i = 0; i < text.length; i++) {
73
+ const ch = text[i];
74
+ if (inQuotes) {
75
+ if (ch === "\\" && i + 1 < text.length) {
76
+ i++;
77
+ continue;
78
+ }
79
+ if (ch === '"') inQuotes = false;
80
+ continue;
81
+ }
82
+ if (ch === '"') {
83
+ inQuotes = true;
84
+ continue;
85
+ }
86
+ if (ch === "(") depth++;
87
+ else if (ch === ")") depth--;
88
+ else if (ch === "," && depth === 0) {
89
+ out.push(text.slice(start, i));
90
+ start = i + 1;
91
+ }
92
+ }
93
+ out.push(text.slice(start));
94
+ return out;
95
+ }
96
+ function parseConstraint(piece) {
97
+ if (piece.length === 0) throw new ScopeParseError("empty constraint");
98
+ const OPS = [">=", "<=", "!=", "=", ">", "<"];
99
+ const wildcardMatch = /^([a-z][a-z0-9_]*)(?:=\*|\*)$/.exec(piece);
100
+ if (wildcardMatch) {
101
+ return { key: wildcardMatch[1], op: "*", value: void 0, quoted: false };
102
+ }
103
+ for (const op of OPS) {
104
+ const idx = piece.indexOf(op);
105
+ if (idx <= 0) continue;
106
+ const key = piece.slice(0, idx);
107
+ if (!IDENT_RE.test(key)) continue;
108
+ const raw = piece.slice(idx + op.length);
109
+ const { value, quoted } = parseValue(raw);
110
+ return { key, op, value, quoted };
111
+ }
112
+ throw new ScopeParseError(`constraint missing operator: ${piece}`);
113
+ }
114
+ function parseValue(raw) {
115
+ if (raw.length === 0) throw new ScopeParseError("constraint value is empty");
116
+ if (raw.startsWith('"')) {
117
+ if (!raw.endsWith('"') || raw.length < 2) {
118
+ throw new ScopeParseError(`unterminated quoted value: ${raw}`);
119
+ }
120
+ let v = "";
121
+ for (let i = 1; i < raw.length - 1; i++) {
122
+ const ch = raw[i];
123
+ if (ch === "\\" && i + 1 < raw.length - 1) {
124
+ const next = raw[++i];
125
+ v += next;
126
+ } else if (ch === '"') {
127
+ throw new ScopeParseError(`unescaped quote in value: ${raw}`);
128
+ } else {
129
+ v += ch;
130
+ }
131
+ }
132
+ return { value: v, quoted: true };
133
+ }
134
+ if (!BARE_TOKEN_RE.test(raw)) {
135
+ throw new ScopeParseError(`invalid bare-token value: ${JSON.stringify(raw)}`);
136
+ }
137
+ return { value: raw, quoted: false };
138
+ }
139
+ function canonicalizeScope(scope) {
140
+ const sorted = [...scope.constraints].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
141
+ const parts = sorted.map(serializeConstraint);
142
+ const inner = parts.join(",");
143
+ return `${scope.product}:${scope.verb}${parts.length === 0 ? "" : `(${inner})`}`;
144
+ }
145
+ function canonicalizeScopeString(input) {
146
+ return canonicalizeScope(parseScope(input));
147
+ }
148
+ function serializeConstraint(c) {
149
+ if (c.op === "*") return `${c.key}=*`;
150
+ const v = c.quoted ? quoteValue(c.value ?? "") : c.value ?? "";
151
+ return `${c.key}${c.op}${v}`;
152
+ }
153
+ function quoteValue(v) {
154
+ let out = '"';
155
+ for (const ch of v) {
156
+ if (ch === '"' || ch === "\\") out += "\\" + ch;
157
+ else out += ch;
158
+ }
159
+ out += '"';
160
+ return out;
161
+ }
162
+ function validateScope(scope, options = {}) {
163
+ const mode = options.mode ?? "strict";
164
+ const reg = REGISTERED_SCOPES[`${scope.product}:${scope.verb}`];
165
+ if (!reg) {
166
+ if (mode === "strict") {
167
+ throw new ScopeParseError(`unregistered scope: ${scope.product}:${scope.verb}`);
168
+ }
169
+ return;
170
+ }
171
+ const registered = new Set(reg.keys);
172
+ for (const c of scope.constraints) {
173
+ if (!registered.has(c.key)) {
174
+ if (mode === "strict") {
175
+ throw new ScopeParseError(
176
+ `unregistered constraint key for ${scope.product}:${scope.verb}: ${c.key}`
177
+ );
178
+ }
179
+ }
180
+ }
181
+ }
182
+ function isSubScope(exercised, granted) {
183
+ if (exercised.product !== granted.product) return false;
184
+ if (exercised.verb !== granted.verb) return false;
185
+ const exIndex = /* @__PURE__ */ new Map();
186
+ for (const c of exercised.constraints) exIndex.set(c.key, c);
187
+ for (const g of granted.constraints) {
188
+ const ex = exIndex.get(g.key);
189
+ if (g.op === "*") continue;
190
+ if (g.op === "=") {
191
+ if (!ex) return false;
192
+ if (ex.op !== "=" || ex.value !== g.value) return false;
193
+ continue;
194
+ }
195
+ if (g.op === "!=") {
196
+ if (!ex) return false;
197
+ if (ex.op === "=" && ex.value !== g.value) continue;
198
+ if (ex.op === "!=" && ex.value === g.value) continue;
199
+ return false;
200
+ }
201
+ if (g.op === "<" || g.op === "<=" || g.op === ">" || g.op === ">=") {
202
+ if (!ex) return false;
203
+ if (!NUMERIC_KEYS.has(g.key)) return false;
204
+ if (ex.op === "*") return false;
205
+ if (ex.value === void 0 || g.value === void 0) return false;
206
+ if (!rangeSubset(ex, g)) return false;
207
+ continue;
208
+ }
209
+ }
210
+ return true;
211
+ }
212
+ function rangeSubset(ex, g) {
213
+ const exRange = opToRange(ex);
214
+ const gRange = opToRange(g);
215
+ if (!exRange || !gRange) return false;
216
+ return gRange.lo <= exRange.lo && exRange.hi <= gRange.hi;
217
+ }
218
+ function opToRange(c) {
219
+ if (c.value === void 0) return null;
220
+ const n = Number(c.value);
221
+ if (!Number.isFinite(n)) return null;
222
+ switch (c.op) {
223
+ case "=":
224
+ return { lo: n, hi: n };
225
+ case "<":
226
+ return { lo: -Infinity, hi: n - 1 };
227
+ // integers only
228
+ case "<=":
229
+ return { lo: -Infinity, hi: n };
230
+ case ">":
231
+ return { lo: n + 1, hi: Infinity };
232
+ case ">=":
233
+ return { lo: n, hi: Infinity };
234
+ default:
235
+ return null;
236
+ }
237
+ }
238
+
239
+ export { REGISTERED_SCOPES, ScopeParseError, canonicalizeScope, canonicalizeScopeString, isSubScope, parseScope, validateScope };
240
+ //# sourceMappingURL=scope.mjs.map
241
+ //# sourceMappingURL=scope.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/scope.ts"],"names":[],"mappings":";AA2BO,IAAM,iBAAA,GAAwD;AAAA,EACjE,aAAa,EAAE,IAAA,EAAM,CAAC,WAAA,EAAa,MAAA,EAAQ,WAAW,CAAA,EAAE;AAAA,EACxD,aAAa,EAAE,IAAA,EAAM,CAAC,WAAA,EAAa,mBAAA,EAAqB,UAAU,CAAA,EAAE;AAAA,EACpE,cAAc,EAAE,IAAA,EAAM,CAAC,MAAA,EAAQ,WAAA,EAAa,qBAAqB,CAAA,EAAE;AAAA,EACnE,aAAa,EAAE,IAAA,EAAM,CAAC,SAAA,EAAW,QAAQ,CAAA,EAAE;AAAA,EAC3C,iBAAiB,EAAE,IAAA,EAAM,CAAC,MAAA,EAAQ,OAAA,EAAS,WAAW,CAAA,EAAE;AAAA,EACxD,cAAA,EAAgB,EAAE,IAAA,EAAM,CAAC,UAAU,QAAA,EAAU,SAAA,EAAW,eAAe,CAAA,EAAE;AAAA,EACzE,WAAW,EAAE,IAAA,EAAM,CAAC,UAAA,EAAY,MAAA,EAAQ,cAAc,CAAA,EAAE;AAAA,EACxD,cAAc,EAAE,IAAA,EAAM,CAAC,QAAA,EAAU,MAAA,EAAQ,iBAAiB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AAU,UAAU,EAAE,CAAA;AAC5B,EAAA,MAAM,MAAA,GAAS,UAAU,CAAC,CAAA;AAC1B,EAAA,IAAI,CAAC,OAAA,IAAW,CAAC,MAAA,EAAQ,OAAO,KAAA;AAChC,EAAA,OAAO,OAAO,EAAA,IAAM,OAAA,CAAQ,EAAA,IAAM,OAAA,CAAQ,MAAM,MAAA,CAAO,EAAA;AAC3D;AAEA,SAAS,UAAU,CAAA,EAAuD;AACtE,EAAA,IAAI,CAAA,CAAE,KAAA,KAAU,MAAA,EAAW,OAAO,IAAA;AAClC,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,CAAA,CAAE,KAAK,CAAA;AACxB,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,CAAC,GAAG,OAAO,IAAA;AAChC,EAAA,QAAQ,EAAE,EAAA;AAAI,IACV,KAAK,GAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,CAAA,EAAG,EAAA,EAAI,CAAA,EAAE;AAAA,IAC1B,KAAK,GAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,CAAA,QAAA,EAAW,EAAA,EAAI,IAAI,CAAA,EAAE;AAAA;AAAA,IACtC,KAAK,IAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,CAAA,QAAA,EAAW,EAAA,EAAI,CAAA,EAAE;AAAA,IAClC,KAAK,GAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,CAAA,GAAI,CAAA,EAAG,IAAI,QAAA,EAAS;AAAA,IACrC,KAAK,IAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,CAAA,EAAG,EAAA,EAAI,QAAA,EAAS;AAAA,IACjC;AACI,MAAA,OAAO,IAAA;AAAA;AAEnB","file":"scope.mjs","sourcesContent":["// Scope grammar, canonicalization, and sub-scope relation. See SPEC.md §7.\n//\n// A scope is <product>:<verb>(<constraint-list>).\n// Constraints are <key><op><value>, op ∈ { =, !=, <, <=, >, >=, * }.\n// Canonical form: constraints sorted by key; no whitespace.\n\nexport type ScopeOp = '=' | '!=' | '<' | '<=' | '>' | '>=' | '*';\n\nexport interface ScopeConstraint {\n key: string;\n op: ScopeOp;\n /** `undefined` for the wildcard `*` op; otherwise the raw textual value (unquoted). */\n value: string | undefined;\n /** True if the value was supplied as a quoted string; preserved for round-trip fidelity. */\n quoted: boolean;\n}\n\nexport interface Scope {\n product: string;\n verb: string;\n constraints: ScopeConstraint[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registered products/verbs (SPEC §7.3) and constraint keys (SPEC §7.6).\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const REGISTERED_SCOPES: Record<string, { keys: string[] }> = {\n 'lock:seal': { keys: ['recipient', 'mime', 'max_bytes'] },\n 'lock:chat': { keys: ['recipient', 'max_bytes_per_msg', 'max_msgs'] },\n 'stamp:sign': { keys: ['mime', 'max_bytes', 'content_hash_prefix'] },\n 'vote:cast': { keys: ['poll_id', 'choice'] },\n 'nostr:publish': { keys: ['kind', 'relay', 'max_bytes'] },\n 'http:request': { keys: ['origin', 'method', 'max_rps', 'max_bytes_out'] },\n 'ln:send': { keys: ['max_sats', 'node', 'max_fee_sats'] },\n 'mcp:invoke': { keys: ['server', 'tool', 'max_invocations'] },\n};\n\n/** Keys whose values are compared numerically for sub-scope ordering. */\nconst NUMERIC_KEYS = new Set<string>([\n 'max_bytes',\n 'max_bytes_per_msg',\n 'max_msgs',\n 'max_bytes_out',\n 'max_rps',\n 'max_sats',\n 'max_fee_sats',\n 'max_invocations',\n 'kind',\n]);\n\nconst IDENT_RE = /^[a-z][a-z0-9_]*$/;\nconst BARE_TOKEN_RE = /^[A-Za-z0-9_.:/@+\\-]+$/;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Parse\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport class ScopeParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ScopeParseError';\n }\n}\n\nexport function parseScope(input: string): Scope {\n if (typeof input !== 'string' || input.length === 0) {\n throw new ScopeParseError('scope must be a non-empty string');\n }\n if (/\\s/.test(input)) {\n throw new ScopeParseError(`scope may not contain whitespace: ${JSON.stringify(input)}`);\n }\n\n const colonIdx = input.indexOf(':');\n if (colonIdx < 0) throw new ScopeParseError('scope missing \"product:verb\" separator');\n\n const product = input.slice(0, colonIdx);\n if (!IDENT_RE.test(product)) throw new ScopeParseError(`invalid product: ${product}`);\n\n const rest = input.slice(colonIdx + 1);\n const parenIdx = rest.indexOf('(');\n\n let verb: string;\n let constraintText = '';\n if (parenIdx < 0) {\n verb = rest;\n } else {\n verb = rest.slice(0, parenIdx);\n if (!rest.endsWith(')')) throw new ScopeParseError('scope constraint list must end with \")\"');\n constraintText = rest.slice(parenIdx + 1, -1);\n }\n if (!IDENT_RE.test(verb)) throw new ScopeParseError(`invalid verb: ${verb}`);\n\n const constraints: ScopeConstraint[] = [];\n if (constraintText.length > 0) {\n for (const piece of splitTopLevelCommas(constraintText)) {\n constraints.push(parseConstraint(piece));\n }\n }\n\n // No duplicate keys.\n const seen = new Set<string>();\n for (const c of constraints) {\n if (seen.has(c.key)) throw new ScopeParseError(`duplicate constraint key: ${c.key}`);\n seen.add(c.key);\n }\n\n return { product, verb, constraints };\n}\n\nfunction splitTopLevelCommas(text: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let inQuotes = false;\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inQuotes) {\n if (ch === '\\\\' && i + 1 < text.length) {\n i++;\n continue;\n }\n if (ch === '\"') inQuotes = false;\n continue;\n }\n if (ch === '\"') {\n inQuotes = true;\n continue;\n }\n if (ch === '(') depth++;\n else if (ch === ')') depth--;\n else if (ch === ',' && depth === 0) {\n out.push(text.slice(start, i));\n start = i + 1;\n }\n }\n out.push(text.slice(start));\n return out;\n}\n\nfunction parseConstraint(piece: string): ScopeConstraint {\n if (piece.length === 0) throw new ScopeParseError('empty constraint');\n\n // The `*` op (wildcard) is an op with no value. Recognized by \"key=*\" form.\n // SPEC uses \"key=*\"; we also accept \"key*\" as legacy alias.\n // Ops in descending length so \">=\" beats \">\" and \"!=\" beats \"!\".\n const OPS: ScopeOp[] = ['>=', '<=', '!=', '=', '>', '<'];\n\n // Special-case wildcard: \"key=*\" or \"key*\".\n const wildcardMatch = /^([a-z][a-z0-9_]*)(?:=\\*|\\*)$/.exec(piece);\n if (wildcardMatch) {\n return { key: wildcardMatch[1]!, op: '*', value: undefined, quoted: false };\n }\n\n for (const op of OPS) {\n const idx = piece.indexOf(op);\n if (idx <= 0) continue; // key must come first and be non-empty\n const key = piece.slice(0, idx);\n if (!IDENT_RE.test(key)) continue;\n const raw = piece.slice(idx + op.length);\n const { value, quoted } = parseValue(raw);\n return { key, op, value, quoted };\n }\n throw new ScopeParseError(`constraint missing operator: ${piece}`);\n}\n\nfunction parseValue(raw: string): { value: string; quoted: boolean } {\n if (raw.length === 0) throw new ScopeParseError('constraint value is empty');\n if (raw.startsWith('\"')) {\n if (!raw.endsWith('\"') || raw.length < 2) {\n throw new ScopeParseError(`unterminated quoted value: ${raw}`);\n }\n let v = '';\n for (let i = 1; i < raw.length - 1; i++) {\n const ch = raw[i]!;\n if (ch === '\\\\' && i + 1 < raw.length - 1) {\n const next = raw[++i]!;\n v += next;\n } else if (ch === '\"') {\n throw new ScopeParseError(`unescaped quote in value: ${raw}`);\n } else {\n v += ch;\n }\n }\n return { value: v, quoted: true };\n }\n if (!BARE_TOKEN_RE.test(raw)) {\n throw new ScopeParseError(`invalid bare-token value: ${JSON.stringify(raw)}`);\n }\n return { value: raw, quoted: false };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalize\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function canonicalizeScope(scope: Scope): string {\n const sorted = [...scope.constraints].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n const parts = sorted.map(serializeConstraint);\n const inner = parts.join(',');\n return `${scope.product}:${scope.verb}${parts.length === 0 ? '' : `(${inner})`}`;\n}\n\nexport function canonicalizeScopeString(input: string): string {\n return canonicalizeScope(parseScope(input));\n}\n\nfunction serializeConstraint(c: ScopeConstraint): string {\n if (c.op === '*') return `${c.key}=*`;\n const v = c.quoted ? quoteValue(c.value ?? '') : c.value ?? '';\n return `${c.key}${c.op}${v}`;\n}\n\nfunction quoteValue(v: string): string {\n let out = '\"';\n for (const ch of v) {\n if (ch === '\"' || ch === '\\\\') out += '\\\\' + ch;\n else out += ch;\n }\n out += '\"';\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registry-based validation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ValidationOptions {\n /**\n * Strict: reject unknown products/verbs and unknown constraint keys.\n * Permissive: accept unknown products/verbs; ignore unknown keys without treating them as wider.\n * Default: 'strict'.\n */\n mode?: 'strict' | 'permissive';\n}\n\nexport function validateScope(scope: Scope, options: ValidationOptions = {}): void {\n const mode = options.mode ?? 'strict';\n const reg = REGISTERED_SCOPES[`${scope.product}:${scope.verb}`];\n if (!reg) {\n if (mode === 'strict') {\n throw new ScopeParseError(`unregistered scope: ${scope.product}:${scope.verb}`);\n }\n return; // permissive: no further checks\n }\n const registered = new Set(reg.keys);\n for (const c of scope.constraints) {\n if (!registered.has(c.key)) {\n if (mode === 'strict') {\n throw new ScopeParseError(\n `unregistered constraint key for ${scope.product}:${scope.verb}: ${c.key}`\n );\n }\n // permissive: ignore\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Sub-scope relation (SPEC §7.4)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Is `exercised` a sub-scope of `granted`?\n * Returns true iff every constraint of `granted` admits the corresponding constraint\n * (or absence) in `exercised`, per SPEC §7.4.\n */\nexport function isSubScope(exercised: Scope, granted: Scope): boolean {\n if (exercised.product !== granted.product) return false;\n if (exercised.verb !== granted.verb) return false;\n\n const exIndex = new Map<string, ScopeConstraint>();\n for (const c of exercised.constraints) exIndex.set(c.key, c);\n\n for (const g of granted.constraints) {\n const ex = exIndex.get(g.key);\n if (g.op === '*') continue; // wildcard: no requirement\n\n if (g.op === '=') {\n if (!ex) return false;\n if (ex.op !== '=' || ex.value !== g.value) return false;\n continue;\n }\n\n if (g.op === '!=') {\n if (!ex) return false;\n if (ex.op === '=' && ex.value !== g.value) continue;\n if (ex.op === '!=' && ex.value === g.value) continue;\n return false;\n }\n\n // Ordered ops: >=, <=, >, <. Exercised's implied range must be ⊆ granted's.\n if (g.op === '<' || g.op === '<=' || g.op === '>' || g.op === '>=') {\n if (!ex) return false;\n if (!NUMERIC_KEYS.has(g.key)) return false;\n if (ex.op === '*') return false;\n if (ex.value === undefined || g.value === undefined) return false;\n if (!rangeSubset(ex, g)) return false;\n continue;\n }\n }\n return true;\n}\n\nfunction rangeSubset(ex: ScopeConstraint, g: ScopeConstraint): boolean {\n const exRange = opToRange(ex);\n const gRange = opToRange(g);\n if (!exRange || !gRange) return false;\n return gRange.lo <= exRange.lo && exRange.hi <= gRange.hi;\n}\n\nfunction opToRange(c: ScopeConstraint): { lo: number; hi: number } | null {\n if (c.value === undefined) return null;\n const n = Number(c.value);\n if (!Number.isFinite(n)) return null;\n switch (c.op) {\n case '=':\n return { lo: n, hi: n };\n case '<':\n return { lo: -Infinity, hi: n - 1 }; // integers only\n case '<=':\n return { lo: -Infinity, hi: n };\n case '>':\n return { lo: n + 1, hi: Infinity };\n case '>=':\n return { lo: n, hi: Infinity };\n default:\n return null;\n }\n}\n"]}
@@ -0,0 +1,127 @@
1
+ declare const ENVELOPE_VERSION: 1;
2
+ type EnvelopeKind = 'agent-delegation' | 'agent-action' | 'agent-revocation';
3
+ interface ActorRef {
4
+ address: string;
5
+ alg: 'bip322';
6
+ }
7
+ interface Signature {
8
+ alg: 'bip322';
9
+ pubkey: string;
10
+ value: string;
11
+ }
12
+ type RevocationHolder = 'principal' | 'agent';
13
+ interface DelegationBond {
14
+ sats: number;
15
+ attestation_id: string;
16
+ }
17
+ interface DelegationRevocationRef {
18
+ holders: RevocationHolder[];
19
+ ref: string | null;
20
+ }
21
+ interface DelegationEnvelope {
22
+ v: typeof ENVELOPE_VERSION;
23
+ kind: 'agent-delegation';
24
+ id: string;
25
+ principal: ActorRef;
26
+ agent: ActorRef;
27
+ scopes: string[];
28
+ bond: DelegationBond | null;
29
+ issued_at: string;
30
+ expires_at: string;
31
+ nonce: string;
32
+ revocation: DelegationRevocationRef;
33
+ sig: Signature;
34
+ }
35
+ interface DelegationCanonicalInput {
36
+ principal: string;
37
+ agent: string;
38
+ scopes: string[];
39
+ bond_sats: number;
40
+ bond_attestation: string;
41
+ issued_at: string;
42
+ expires_at: string;
43
+ nonce: string;
44
+ }
45
+ interface ActionContent {
46
+ hash: string;
47
+ length: number;
48
+ mime: string;
49
+ ref: string | null;
50
+ }
51
+ interface ActionOts {
52
+ status: 'pending' | 'confirmed';
53
+ proof: string;
54
+ calendars: string[];
55
+ block_height: number | null;
56
+ block_hash: string | null;
57
+ upgraded_at: string | null;
58
+ }
59
+ interface ActionEnvelope {
60
+ v: typeof ENVELOPE_VERSION;
61
+ kind: 'agent-action';
62
+ id: string;
63
+ content: ActionContent;
64
+ signer: ActorRef;
65
+ signed_at: string;
66
+ delegation_id: string;
67
+ scope_exercised: string;
68
+ ots: ActionOts | null;
69
+ sig: Signature;
70
+ }
71
+ interface ActionCanonicalInput {
72
+ address: string;
73
+ content_hash: string;
74
+ content_length: number;
75
+ content_mime: string;
76
+ signed_at: string;
77
+ delegation_id: string;
78
+ scope_exercised: string;
79
+ }
80
+ interface RevocationEnvelope {
81
+ v: typeof ENVELOPE_VERSION;
82
+ kind: 'agent-revocation';
83
+ id: string;
84
+ delegation_id: string;
85
+ signer: ActorRef;
86
+ reason: string;
87
+ signed_at: string;
88
+ ots: ActionOts | null;
89
+ sig: Signature;
90
+ }
91
+ interface RevocationCanonicalInput {
92
+ address: string;
93
+ delegation_id: string;
94
+ reason: string;
95
+ signed_at: string;
96
+ }
97
+ type AgentErrorCode = 'E_UNSUPPORTED_VERSION' | 'E_MALFORMED' | 'E_BAD_ID' | 'E_BAD_SIG' | 'E_BAD_SCOPE_GRAMMAR' | 'E_NOT_YET_VALID' | 'E_EXPIRED' | 'E_REVOKED' | 'E_DELEGATION_MISMATCH' | 'E_AGENT_MISMATCH' | 'E_OUT_OF_WINDOW' | 'E_SCOPE_DENIED' | 'E_BAD_ACTION_STAMP' | 'E_NO_BOND' | 'E_BOND_UNMET' | 'E_BOND_UNVERIFIED' | 'E_REVOKER_UNAUTHORIZED' | 'E_CALENDAR_UNREACHABLE';
98
+ interface VerifyOk<T> {
99
+ ok: true;
100
+ envelope: T;
101
+ canonicalMessage: string;
102
+ id: string;
103
+ }
104
+ interface VerifyErr {
105
+ ok: false;
106
+ code: AgentErrorCode;
107
+ message: string;
108
+ }
109
+ type VerifyDelegationResult = VerifyOk<DelegationEnvelope> | VerifyErr;
110
+ type VerifyRevocationResult = VerifyOk<RevocationEnvelope> | VerifyErr;
111
+ interface VerifyActionOkExtra {
112
+ delegation: DelegationEnvelope;
113
+ scopeExercised: string;
114
+ anchor: {
115
+ status: 'none';
116
+ } | {
117
+ status: 'pending';
118
+ } | {
119
+ status: 'confirmed';
120
+ blockHeight: number;
121
+ blockHash: string;
122
+ verified: boolean;
123
+ };
124
+ }
125
+ type VerifyActionResult = (VerifyOk<ActionEnvelope> & VerifyActionOkExtra) | VerifyErr;
126
+
127
+ export { type ActionCanonicalInput, type ActionContent, type ActionEnvelope, type ActionOts, type ActorRef, type AgentErrorCode, type DelegationBond, type DelegationCanonicalInput, type DelegationEnvelope, type DelegationRevocationRef, ENVELOPE_VERSION, type EnvelopeKind, type RevocationCanonicalInput, type RevocationEnvelope, type RevocationHolder, type Signature, type VerifyActionOkExtra, type VerifyActionResult, type VerifyDelegationResult, type VerifyErr, type VerifyOk, type VerifyRevocationResult };
@@ -0,0 +1,127 @@
1
+ declare const ENVELOPE_VERSION: 1;
2
+ type EnvelopeKind = 'agent-delegation' | 'agent-action' | 'agent-revocation';
3
+ interface ActorRef {
4
+ address: string;
5
+ alg: 'bip322';
6
+ }
7
+ interface Signature {
8
+ alg: 'bip322';
9
+ pubkey: string;
10
+ value: string;
11
+ }
12
+ type RevocationHolder = 'principal' | 'agent';
13
+ interface DelegationBond {
14
+ sats: number;
15
+ attestation_id: string;
16
+ }
17
+ interface DelegationRevocationRef {
18
+ holders: RevocationHolder[];
19
+ ref: string | null;
20
+ }
21
+ interface DelegationEnvelope {
22
+ v: typeof ENVELOPE_VERSION;
23
+ kind: 'agent-delegation';
24
+ id: string;
25
+ principal: ActorRef;
26
+ agent: ActorRef;
27
+ scopes: string[];
28
+ bond: DelegationBond | null;
29
+ issued_at: string;
30
+ expires_at: string;
31
+ nonce: string;
32
+ revocation: DelegationRevocationRef;
33
+ sig: Signature;
34
+ }
35
+ interface DelegationCanonicalInput {
36
+ principal: string;
37
+ agent: string;
38
+ scopes: string[];
39
+ bond_sats: number;
40
+ bond_attestation: string;
41
+ issued_at: string;
42
+ expires_at: string;
43
+ nonce: string;
44
+ }
45
+ interface ActionContent {
46
+ hash: string;
47
+ length: number;
48
+ mime: string;
49
+ ref: string | null;
50
+ }
51
+ interface ActionOts {
52
+ status: 'pending' | 'confirmed';
53
+ proof: string;
54
+ calendars: string[];
55
+ block_height: number | null;
56
+ block_hash: string | null;
57
+ upgraded_at: string | null;
58
+ }
59
+ interface ActionEnvelope {
60
+ v: typeof ENVELOPE_VERSION;
61
+ kind: 'agent-action';
62
+ id: string;
63
+ content: ActionContent;
64
+ signer: ActorRef;
65
+ signed_at: string;
66
+ delegation_id: string;
67
+ scope_exercised: string;
68
+ ots: ActionOts | null;
69
+ sig: Signature;
70
+ }
71
+ interface ActionCanonicalInput {
72
+ address: string;
73
+ content_hash: string;
74
+ content_length: number;
75
+ content_mime: string;
76
+ signed_at: string;
77
+ delegation_id: string;
78
+ scope_exercised: string;
79
+ }
80
+ interface RevocationEnvelope {
81
+ v: typeof ENVELOPE_VERSION;
82
+ kind: 'agent-revocation';
83
+ id: string;
84
+ delegation_id: string;
85
+ signer: ActorRef;
86
+ reason: string;
87
+ signed_at: string;
88
+ ots: ActionOts | null;
89
+ sig: Signature;
90
+ }
91
+ interface RevocationCanonicalInput {
92
+ address: string;
93
+ delegation_id: string;
94
+ reason: string;
95
+ signed_at: string;
96
+ }
97
+ type AgentErrorCode = 'E_UNSUPPORTED_VERSION' | 'E_MALFORMED' | 'E_BAD_ID' | 'E_BAD_SIG' | 'E_BAD_SCOPE_GRAMMAR' | 'E_NOT_YET_VALID' | 'E_EXPIRED' | 'E_REVOKED' | 'E_DELEGATION_MISMATCH' | 'E_AGENT_MISMATCH' | 'E_OUT_OF_WINDOW' | 'E_SCOPE_DENIED' | 'E_BAD_ACTION_STAMP' | 'E_NO_BOND' | 'E_BOND_UNMET' | 'E_BOND_UNVERIFIED' | 'E_REVOKER_UNAUTHORIZED' | 'E_CALENDAR_UNREACHABLE';
98
+ interface VerifyOk<T> {
99
+ ok: true;
100
+ envelope: T;
101
+ canonicalMessage: string;
102
+ id: string;
103
+ }
104
+ interface VerifyErr {
105
+ ok: false;
106
+ code: AgentErrorCode;
107
+ message: string;
108
+ }
109
+ type VerifyDelegationResult = VerifyOk<DelegationEnvelope> | VerifyErr;
110
+ type VerifyRevocationResult = VerifyOk<RevocationEnvelope> | VerifyErr;
111
+ interface VerifyActionOkExtra {
112
+ delegation: DelegationEnvelope;
113
+ scopeExercised: string;
114
+ anchor: {
115
+ status: 'none';
116
+ } | {
117
+ status: 'pending';
118
+ } | {
119
+ status: 'confirmed';
120
+ blockHeight: number;
121
+ blockHash: string;
122
+ verified: boolean;
123
+ };
124
+ }
125
+ type VerifyActionResult = (VerifyOk<ActionEnvelope> & VerifyActionOkExtra) | VerifyErr;
126
+
127
+ export { type ActionCanonicalInput, type ActionContent, type ActionEnvelope, type ActionOts, type ActorRef, type AgentErrorCode, type DelegationBond, type DelegationCanonicalInput, type DelegationEnvelope, type DelegationRevocationRef, ENVELOPE_VERSION, type EnvelopeKind, type RevocationCanonicalInput, type RevocationEnvelope, type RevocationHolder, type Signature, type VerifyActionOkExtra, type VerifyActionResult, type VerifyDelegationResult, type VerifyErr, type VerifyOk, type VerifyRevocationResult };
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ // src/types.ts
4
+ var ENVELOPE_VERSION = 1;
5
+
6
+ exports.ENVELOPE_VERSION = ENVELOPE_VERSION;
7
+ //# sourceMappingURL=types.js.map
8
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";;;AAEO,IAAM,gBAAA,GAAmB","file":"types.js","sourcesContent":["// Wire types for OC Agent v1 envelopes. See SPEC.md §4, §5, §9.\n\nexport const ENVELOPE_VERSION = 1 as const;\n\nexport type EnvelopeKind = 'agent-delegation' | 'agent-action' | 'agent-revocation';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared building blocks\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActorRef {\n /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */\n address: string;\n alg: 'bip322';\n}\n\nexport interface Signature {\n alg: 'bip322';\n pubkey: string; // equals the producing actor's address\n value: string; // base64 BIP-322 signature over hex(id)\n}\n\nexport type RevocationHolder = 'principal' | 'agent';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation (SPEC §4)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface DelegationBond {\n /** Non-negative sats declared as bonded at issuance time. */\n sats: number;\n /** SHA-256 hex of the OrangeCheck canonical message signed by principal.address. */\n attestation_id: string;\n}\n\nexport interface DelegationRevocationRef {\n /** Who MAY publish a revocation. Default [\"principal\"]. */\n holders: RevocationHolder[];\n /** Optional Nostr-addressable pointer to a published revocation. Non-cryptographic. */\n ref: string | null;\n}\n\nexport interface DelegationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-delegation';\n id: string; // 64-hex sha256(canonical_message)\n principal: ActorRef;\n agent: ActorRef;\n /** Sorted lexicographically in the canonical message; stored in sorted order on the envelope too. */\n scopes: string[];\n bond: DelegationBond | null;\n issued_at: string; // ISO 8601 UTC\n expires_at: string; // ISO 8601 UTC\n nonce: string; // 32-hex random\n revocation: DelegationRevocationRef;\n sig: Signature;\n}\n\nexport interface DelegationCanonicalInput {\n principal: string;\n agent: string;\n scopes: string[]; // pre-canonicalized, pre-sorted\n bond_sats: number;\n /** 64-hex attestation id or the literal string \"none\". */\n bond_attestation: string;\n issued_at: string;\n expires_at: string;\n nonce: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Agent-action (SPEC §5) — strict extension of OC Stamp\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActionContent {\n hash: string; // \"sha256:<64-hex>\"\n length: number;\n mime: string;\n ref: string | null;\n}\n\nexport interface ActionOts {\n status: 'pending' | 'confirmed';\n proof: string;\n calendars: string[];\n block_height: number | null;\n block_hash: string | null;\n upgraded_at: string | null;\n}\n\nexport interface ActionEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-action';\n id: string;\n content: ActionContent;\n signer: ActorRef; // agent\n signed_at: string;\n delegation_id: string; // 64-hex\n scope_exercised: string; // a sub-scope of some granted scope\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface ActionCanonicalInput {\n address: string; // agent address\n content_hash: string;\n content_length: number;\n content_mime: string;\n signed_at: string;\n delegation_id: string;\n scope_exercised: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation (SPEC §9)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface RevocationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-revocation';\n id: string;\n delegation_id: string;\n signer: ActorRef;\n /** Short ASCII rationale, <= 128 bytes. Empty string if omitted. */\n reason: string;\n signed_at: string;\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface RevocationCanonicalInput {\n address: string;\n delegation_id: string;\n reason: string;\n signed_at: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error codes (SPEC §11)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type AgentErrorCode =\n | 'E_UNSUPPORTED_VERSION'\n | 'E_MALFORMED'\n | 'E_BAD_ID'\n | 'E_BAD_SIG'\n | 'E_BAD_SCOPE_GRAMMAR'\n | 'E_NOT_YET_VALID'\n | 'E_EXPIRED'\n | 'E_REVOKED'\n | 'E_DELEGATION_MISMATCH'\n | 'E_AGENT_MISMATCH'\n | 'E_OUT_OF_WINDOW'\n | 'E_SCOPE_DENIED'\n | 'E_BAD_ACTION_STAMP'\n | 'E_NO_BOND'\n | 'E_BOND_UNMET'\n | 'E_BOND_UNVERIFIED'\n | 'E_REVOKER_UNAUTHORIZED'\n | 'E_CALENDAR_UNREACHABLE';\n\nexport interface VerifyOk<T> {\n ok: true;\n envelope: T;\n canonicalMessage: string;\n id: string;\n}\n\nexport interface VerifyErr {\n ok: false;\n code: AgentErrorCode;\n message: string;\n}\n\nexport type VerifyDelegationResult = VerifyOk<DelegationEnvelope> | VerifyErr;\nexport type VerifyRevocationResult = VerifyOk<RevocationEnvelope> | VerifyErr;\n\nexport interface VerifyActionOkExtra {\n delegation: DelegationEnvelope;\n scopeExercised: string;\n anchor:\n | { status: 'none' }\n | { status: 'pending' }\n | { status: 'confirmed'; blockHeight: number; blockHash: string; verified: boolean };\n}\n\nexport type VerifyActionResult =\n | (VerifyOk<ActionEnvelope> & VerifyActionOkExtra)\n | VerifyErr;\n"]}
package/dist/types.mjs ADDED
@@ -0,0 +1,6 @@
1
+ // src/types.ts
2
+ var ENVELOPE_VERSION = 1;
3
+
4
+ export { ENVELOPE_VERSION };
5
+ //# sourceMappingURL=types.mjs.map
6
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";AAEO,IAAM,gBAAA,GAAmB","file":"types.mjs","sourcesContent":["// Wire types for OC Agent v1 envelopes. See SPEC.md §4, §5, §9.\n\nexport const ENVELOPE_VERSION = 1 as const;\n\nexport type EnvelopeKind = 'agent-delegation' | 'agent-action' | 'agent-revocation';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared building blocks\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActorRef {\n /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */\n address: string;\n alg: 'bip322';\n}\n\nexport interface Signature {\n alg: 'bip322';\n pubkey: string; // equals the producing actor's address\n value: string; // base64 BIP-322 signature over hex(id)\n}\n\nexport type RevocationHolder = 'principal' | 'agent';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Delegation (SPEC §4)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface DelegationBond {\n /** Non-negative sats declared as bonded at issuance time. */\n sats: number;\n /** SHA-256 hex of the OrangeCheck canonical message signed by principal.address. */\n attestation_id: string;\n}\n\nexport interface DelegationRevocationRef {\n /** Who MAY publish a revocation. Default [\"principal\"]. */\n holders: RevocationHolder[];\n /** Optional Nostr-addressable pointer to a published revocation. Non-cryptographic. */\n ref: string | null;\n}\n\nexport interface DelegationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-delegation';\n id: string; // 64-hex sha256(canonical_message)\n principal: ActorRef;\n agent: ActorRef;\n /** Sorted lexicographically in the canonical message; stored in sorted order on the envelope too. */\n scopes: string[];\n bond: DelegationBond | null;\n issued_at: string; // ISO 8601 UTC\n expires_at: string; // ISO 8601 UTC\n nonce: string; // 32-hex random\n revocation: DelegationRevocationRef;\n sig: Signature;\n}\n\nexport interface DelegationCanonicalInput {\n principal: string;\n agent: string;\n scopes: string[]; // pre-canonicalized, pre-sorted\n bond_sats: number;\n /** 64-hex attestation id or the literal string \"none\". */\n bond_attestation: string;\n issued_at: string;\n expires_at: string;\n nonce: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Agent-action (SPEC §5) — strict extension of OC Stamp\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActionContent {\n hash: string; // \"sha256:<64-hex>\"\n length: number;\n mime: string;\n ref: string | null;\n}\n\nexport interface ActionOts {\n status: 'pending' | 'confirmed';\n proof: string;\n calendars: string[];\n block_height: number | null;\n block_hash: string | null;\n upgraded_at: string | null;\n}\n\nexport interface ActionEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-action';\n id: string;\n content: ActionContent;\n signer: ActorRef; // agent\n signed_at: string;\n delegation_id: string; // 64-hex\n scope_exercised: string; // a sub-scope of some granted scope\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface ActionCanonicalInput {\n address: string; // agent address\n content_hash: string;\n content_length: number;\n content_mime: string;\n signed_at: string;\n delegation_id: string;\n scope_exercised: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Revocation (SPEC §9)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface RevocationEnvelope {\n v: typeof ENVELOPE_VERSION;\n kind: 'agent-revocation';\n id: string;\n delegation_id: string;\n signer: ActorRef;\n /** Short ASCII rationale, <= 128 bytes. Empty string if omitted. */\n reason: string;\n signed_at: string;\n ots: ActionOts | null;\n sig: Signature;\n}\n\nexport interface RevocationCanonicalInput {\n address: string;\n delegation_id: string;\n reason: string;\n signed_at: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error codes (SPEC §11)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type AgentErrorCode =\n | 'E_UNSUPPORTED_VERSION'\n | 'E_MALFORMED'\n | 'E_BAD_ID'\n | 'E_BAD_SIG'\n | 'E_BAD_SCOPE_GRAMMAR'\n | 'E_NOT_YET_VALID'\n | 'E_EXPIRED'\n | 'E_REVOKED'\n | 'E_DELEGATION_MISMATCH'\n | 'E_AGENT_MISMATCH'\n | 'E_OUT_OF_WINDOW'\n | 'E_SCOPE_DENIED'\n | 'E_BAD_ACTION_STAMP'\n | 'E_NO_BOND'\n | 'E_BOND_UNMET'\n | 'E_BOND_UNVERIFIED'\n | 'E_REVOKER_UNAUTHORIZED'\n | 'E_CALENDAR_UNREACHABLE';\n\nexport interface VerifyOk<T> {\n ok: true;\n envelope: T;\n canonicalMessage: string;\n id: string;\n}\n\nexport interface VerifyErr {\n ok: false;\n code: AgentErrorCode;\n message: string;\n}\n\nexport type VerifyDelegationResult = VerifyOk<DelegationEnvelope> | VerifyErr;\nexport type VerifyRevocationResult = VerifyOk<RevocationEnvelope> | VerifyErr;\n\nexport interface VerifyActionOkExtra {\n delegation: DelegationEnvelope;\n scopeExercised: string;\n anchor:\n | { status: 'none' }\n | { status: 'pending' }\n | { status: 'confirmed'; blockHeight: number; blockHash: string; verified: boolean };\n}\n\nexport type VerifyActionResult =\n | (VerifyOk<ActionEnvelope> & VerifyActionOkExtra)\n | VerifyErr;\n"]}