openadapt-kernel 0.1.0__py3-none-any.whl
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.
- openadapt_kernel/__init__.py +147 -0
- openadapt_kernel/aci.py +82 -0
- openadapt_kernel/cli.py +215 -0
- openadapt_kernel/copilot.py +338 -0
- openadapt_kernel/extension_bridge.py +134 -0
- openadapt_kernel/fsm.py +198 -0
- openadapt_kernel/interceptor.py +262 -0
- openadapt_kernel/ledger.py +379 -0
- openadapt_kernel/macro.py +354 -0
- openadapt_kernel/mcp_server.py +224 -0
- openadapt_kernel/oracles.py +317 -0
- openadapt_kernel/probe.py +100 -0
- openadapt_kernel/registry.py +145 -0
- openadapt_kernel/runner.py +292 -0
- openadapt_kernel-0.1.0.dist-info/METADATA +52 -0
- openadapt_kernel-0.1.0.dist-info/RECORD +19 -0
- openadapt_kernel-0.1.0.dist-info/WHEEL +4 -0
- openadapt_kernel-0.1.0.dist-info/entry_points.txt +2 -0
- openadapt_kernel-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Full-DOM schema extraction, transactional form staging, and stepwise live-DOM healing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
from openadapt_kernel.interceptor import CommitInterceptor
|
|
10
|
+
from openadapt_kernel.ledger import ObligationLedger, ProvenanceViolation
|
|
11
|
+
|
|
12
|
+
_OBSERVE_SCHEMA_JS = """() => {
|
|
13
|
+
const nodes = document.querySelectorAll(
|
|
14
|
+
'input, textarea, select, button, a[href], [role="button"], [role="textbox"], [role="combobox"], [role="checkbox"]'
|
|
15
|
+
);
|
|
16
|
+
const items = [];
|
|
17
|
+
const labelTextFor = (el) => {
|
|
18
|
+
if (el.getAttribute('aria-label')) return el.getAttribute('aria-label').trim();
|
|
19
|
+
if (el.id) {
|
|
20
|
+
const lbl = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
|
|
21
|
+
if (lbl) return (lbl.innerText || lbl.textContent || '').trim();
|
|
22
|
+
}
|
|
23
|
+
const parentLabel = el.closest('label');
|
|
24
|
+
if (parentLabel) return (parentLabel.innerText || parentLabel.textContent || '').trim();
|
|
25
|
+
if (el.placeholder) return el.placeholder.trim();
|
|
26
|
+
const txt = (el.innerText || el.textContent || '').trim();
|
|
27
|
+
return txt.slice(0, 120);
|
|
28
|
+
};
|
|
29
|
+
const cssSelectorFor = (el) => {
|
|
30
|
+
const tid = el.getAttribute('data-testid');
|
|
31
|
+
if (tid) return `[data-testid="${tid.replace(/"/g, '\\\\"')}"]`;
|
|
32
|
+
if (el.id) return `#${CSS.escape(el.id)}`;
|
|
33
|
+
const name = el.getAttribute('name');
|
|
34
|
+
if (name) return `${el.tagName.toLowerCase()}[name="${name.replace(/"/g, '\\\\"')}"]`;
|
|
35
|
+
const aria = el.getAttribute('aria-label');
|
|
36
|
+
if (aria) return `${el.tagName.toLowerCase()}[aria-label="${aria.replace(/"/g, '\\\\"')}"]`;
|
|
37
|
+
return '';
|
|
38
|
+
};
|
|
39
|
+
const modalRoot = document.querySelector('[role="dialog"], .v-dialog--active, .modal.show, dialog[open]');
|
|
40
|
+
for (const el of nodes) {
|
|
41
|
+
const st = window.getComputedStyle(el);
|
|
42
|
+
if (!st || st.display === 'none' || st.visibility === 'hidden') continue;
|
|
43
|
+
const type = (el.getAttribute('type') || '').toLowerCase();
|
|
44
|
+
if (type === 'hidden') continue;
|
|
45
|
+
const rect = el.getBoundingClientRect();
|
|
46
|
+
if (rect.width === 0 && rect.height === 0) continue;
|
|
47
|
+
const tag = el.tagName.toLowerCase();
|
|
48
|
+
const role = (el.getAttribute('role') || '').toLowerCase();
|
|
49
|
+
const inModal = Boolean(modalRoot && modalRoot.contains(el));
|
|
50
|
+
const options = tag === 'select'
|
|
51
|
+
? Array.from(el.options).map(o => ({ value: o.value, text: (o.text || '').trim() }))
|
|
52
|
+
: [];
|
|
53
|
+
items.push({
|
|
54
|
+
tag,
|
|
55
|
+
input_type: type,
|
|
56
|
+
role,
|
|
57
|
+
label: labelTextFor(el),
|
|
58
|
+
placeholder: (el.getAttribute('placeholder') || '').trim(),
|
|
59
|
+
name: (el.getAttribute('name') || '').trim(),
|
|
60
|
+
element_id: (el.id || '').trim(),
|
|
61
|
+
testid: (el.getAttribute('data-testid') || '').trim(),
|
|
62
|
+
in_modal: inModal,
|
|
63
|
+
selector: cssSelectorFor(el),
|
|
64
|
+
value: tag === 'input' && (type === 'checkbox' || type === 'radio')
|
|
65
|
+
? String(Boolean(el.checked))
|
|
66
|
+
: String(el.value !== undefined ? el.value : ''),
|
|
67
|
+
options,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return items;
|
|
71
|
+
}"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class ControlSchema:
|
|
76
|
+
tag: str
|
|
77
|
+
input_type: str
|
|
78
|
+
role: str
|
|
79
|
+
label: str
|
|
80
|
+
placeholder: str
|
|
81
|
+
name: str
|
|
82
|
+
element_id: str
|
|
83
|
+
testid: str
|
|
84
|
+
in_modal: bool
|
|
85
|
+
selector: str
|
|
86
|
+
value: str = ""
|
|
87
|
+
options: List[Dict[str, str]] = field(default_factory=list)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class StageResult:
|
|
92
|
+
ok: bool
|
|
93
|
+
staged: Dict[str, str] = field(default_factory=dict)
|
|
94
|
+
mismatched: Dict[str, str] = field(default_factory=dict)
|
|
95
|
+
unmatched: List[str] = field(default_factory=list)
|
|
96
|
+
provenance_violations: List[ProvenanceViolation] = field(default_factory=list)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class PlanStep:
|
|
101
|
+
step_id: str
|
|
102
|
+
action: Literal["click", "fill", "select", "check"]
|
|
103
|
+
selector: str
|
|
104
|
+
semantic_label: str
|
|
105
|
+
value: Optional[str] = None
|
|
106
|
+
is_commit: bool = False
|
|
107
|
+
prefer_modal: bool = False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class HealResult:
|
|
112
|
+
verified: bool
|
|
113
|
+
healed_steps: List[str] = field(default_factory=list)
|
|
114
|
+
healed_plan: List[PlanStep] = field(default_factory=list)
|
|
115
|
+
failure_reason: str = ""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _tokens(text: str) -> set[str]:
|
|
119
|
+
return set(re.findall(r"[a-z0-9]+", (text or "").lower()))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def observe_schema(page: Any) -> List[ControlSchema]:
|
|
123
|
+
"""Extract all visible interactive controls across the full scrollable page."""
|
|
124
|
+
raw_items = page.evaluate(_OBSERVE_SCHEMA_JS) or []
|
|
125
|
+
return [ControlSchema(**item) for item in raw_items]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _match_control(
|
|
129
|
+
key: str,
|
|
130
|
+
controls: Sequence[ControlSchema],
|
|
131
|
+
*,
|
|
132
|
+
prefer_modal: bool = False,
|
|
133
|
+
allowed_tags: Optional[Sequence[str]] = None,
|
|
134
|
+
) -> Optional[ControlSchema]:
|
|
135
|
+
key_l = key.strip().lower()
|
|
136
|
+
key_toks = _tokens(key)
|
|
137
|
+
best: Optional[ControlSchema] = None
|
|
138
|
+
best_score = 0.0
|
|
139
|
+
|
|
140
|
+
for ctrl in controls:
|
|
141
|
+
if allowed_tags and ctrl.tag not in allowed_tags:
|
|
142
|
+
continue
|
|
143
|
+
score = 0.0
|
|
144
|
+
if ctrl.selector and ctrl.selector.lower() == key_l:
|
|
145
|
+
score = 100.0
|
|
146
|
+
elif ctrl.testid and ctrl.testid.lower() == key_l:
|
|
147
|
+
score = 95.0
|
|
148
|
+
elif ctrl.name and ctrl.name.lower() == key_l:
|
|
149
|
+
score = 90.0
|
|
150
|
+
elif ctrl.element_id and ctrl.element_id.lower() == key_l:
|
|
151
|
+
score = 88.0
|
|
152
|
+
elif ctrl.label and ctrl.label.lower() == key_l:
|
|
153
|
+
score = 85.0
|
|
154
|
+
elif ctrl.placeholder and ctrl.placeholder.lower() == key_l:
|
|
155
|
+
score = 80.0
|
|
156
|
+
else:
|
|
157
|
+
cand_toks = _tokens(f"{ctrl.label} {ctrl.placeholder} {ctrl.name} {ctrl.testid} {ctrl.element_id}")
|
|
158
|
+
if key_toks and cand_toks:
|
|
159
|
+
overlap = len(key_toks & cand_toks) / len(key_toks)
|
|
160
|
+
if overlap >= 0.5:
|
|
161
|
+
score = 50.0 * overlap
|
|
162
|
+
if score > 0.0 and prefer_modal and ctrl.in_modal:
|
|
163
|
+
score += 20.0
|
|
164
|
+
if score > best_score:
|
|
165
|
+
best_score = score
|
|
166
|
+
best = ctrl
|
|
167
|
+
return best
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _resolve_locator(page: Any, ctrl: ControlSchema) -> Any:
|
|
171
|
+
if ctrl.selector:
|
|
172
|
+
return page.locator(ctrl.selector).first
|
|
173
|
+
if ctrl.label and ctrl.tag in ("button", "a"):
|
|
174
|
+
return page.locator(f"{ctrl.tag}:has-text({ctrl.label!r})").first
|
|
175
|
+
raise ValueError(f"Control lacks deterministic selector: {ctrl}")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def stage_form(
|
|
179
|
+
page: Any,
|
|
180
|
+
bindings: Dict[str, str],
|
|
181
|
+
*,
|
|
182
|
+
ledger: Optional[ObligationLedger] = None,
|
|
183
|
+
opaque_fields: Iterable[str] = (),
|
|
184
|
+
interceptor: Optional[CommitInterceptor] = None,
|
|
185
|
+
subject_key: Optional[str] = None,
|
|
186
|
+
prefer_modal: bool = False,
|
|
187
|
+
) -> StageResult:
|
|
188
|
+
"""Fill an entire form in one pre-commit batch and verify every DOM value."""
|
|
189
|
+
if ledger is not None and opaque_fields:
|
|
190
|
+
violations = ledger.verify_ssa_provenance(
|
|
191
|
+
bindings, opaque_fields=opaque_fields, target_subject_key=subject_key
|
|
192
|
+
)
|
|
193
|
+
if violations:
|
|
194
|
+
return StageResult(ok=False, provenance_violations=violations)
|
|
195
|
+
|
|
196
|
+
controls = observe_schema(page)
|
|
197
|
+
input_controls = [c for c in controls if c.tag in ("input", "textarea", "select")]
|
|
198
|
+
result = StageResult(ok=True)
|
|
199
|
+
|
|
200
|
+
for key, val in bindings.items():
|
|
201
|
+
ctrl = _match_control(key, input_controls, prefer_modal=prefer_modal)
|
|
202
|
+
if ctrl is None:
|
|
203
|
+
result.unmatched.append(key)
|
|
204
|
+
result.ok = False
|
|
205
|
+
continue
|
|
206
|
+
|
|
207
|
+
loc = _resolve_locator(page, ctrl)
|
|
208
|
+
loc.scroll_into_view_if_needed()
|
|
209
|
+
|
|
210
|
+
if ctrl.tag == "select":
|
|
211
|
+
loc.select_option(val)
|
|
212
|
+
actual = str(loc.input_value())
|
|
213
|
+
matched = actual == val or any(
|
|
214
|
+
o["text"].lower() == val.lower() and o["value"] == actual for o in ctrl.options
|
|
215
|
+
)
|
|
216
|
+
elif ctrl.input_type in ("checkbox", "radio"):
|
|
217
|
+
want_checked = str(val).strip().lower() in ("true", "1", "yes", "checked")
|
|
218
|
+
if want_checked:
|
|
219
|
+
loc.check()
|
|
220
|
+
else:
|
|
221
|
+
loc.uncheck()
|
|
222
|
+
actual = str(bool(loc.is_checked()))
|
|
223
|
+
matched = bool(loc.is_checked()) == want_checked
|
|
224
|
+
else:
|
|
225
|
+
loc.fill(str(val))
|
|
226
|
+
actual = str(loc.input_value())
|
|
227
|
+
matched = actual == str(val)
|
|
228
|
+
|
|
229
|
+
if matched:
|
|
230
|
+
result.staged[key] = actual
|
|
231
|
+
if interceptor is not None:
|
|
232
|
+
interceptor.mark_field_edited(
|
|
233
|
+
ctrl.testid or ctrl.name or ctrl.element_id or key,
|
|
234
|
+
actual,
|
|
235
|
+
input_type=ctrl.input_type,
|
|
236
|
+
aria_role=ctrl.role,
|
|
237
|
+
label=ctrl.label,
|
|
238
|
+
)
|
|
239
|
+
else:
|
|
240
|
+
result.mismatched[key] = f"expected={val!r}, actual={actual!r}"
|
|
241
|
+
result.ok = False
|
|
242
|
+
|
|
243
|
+
return result
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class StepwiseHealer:
|
|
247
|
+
"""Replays compiled plans and re-grounds broken steps against the live mounted DOM."""
|
|
248
|
+
|
|
249
|
+
def __init__(
|
|
250
|
+
self,
|
|
251
|
+
llm_selector_fn: Optional[Callable[[PlanStep, List[ControlSchema]], Optional[str]]] = None,
|
|
252
|
+
) -> None:
|
|
253
|
+
self._llm_selector_fn = llm_selector_fn
|
|
254
|
+
|
|
255
|
+
def _execute_step(self, page: Any, step: PlanStep, selector: str) -> None:
|
|
256
|
+
loc = page.locator(selector).first
|
|
257
|
+
loc.wait_for(state="visible", timeout=1500)
|
|
258
|
+
loc.scroll_into_view_if_needed()
|
|
259
|
+
if step.action == "click":
|
|
260
|
+
loc.click()
|
|
261
|
+
elif step.action == "fill":
|
|
262
|
+
loc.fill(str(step.value or ""))
|
|
263
|
+
if str(loc.input_value()) != str(step.value or ""):
|
|
264
|
+
raise RuntimeError(f"Postcondition mismatch on {selector}")
|
|
265
|
+
elif step.action == "select":
|
|
266
|
+
loc.select_option(str(step.value or ""))
|
|
267
|
+
elif step.action == "check":
|
|
268
|
+
if str(step.value or "true").lower() in ("true", "1", "yes"):
|
|
269
|
+
loc.check()
|
|
270
|
+
else:
|
|
271
|
+
loc.uncheck()
|
|
272
|
+
|
|
273
|
+
def _heal_live_step(self, page: Any, step: PlanStep) -> Optional[str]:
|
|
274
|
+
controls = observe_schema(page)
|
|
275
|
+
if self._llm_selector_fn is not None:
|
|
276
|
+
proposed = self._llm_selector_fn(step, controls)
|
|
277
|
+
if proposed:
|
|
278
|
+
return proposed
|
|
279
|
+
allowed = (
|
|
280
|
+
("button", "a")
|
|
281
|
+
if step.action == "click"
|
|
282
|
+
else ("select",)
|
|
283
|
+
if step.action == "select"
|
|
284
|
+
else ("input", "textarea")
|
|
285
|
+
)
|
|
286
|
+
ctrl = _match_control(
|
|
287
|
+
step.semantic_label,
|
|
288
|
+
controls,
|
|
289
|
+
prefer_modal=step.prefer_modal or any(c.in_modal for c in controls),
|
|
290
|
+
allowed_tags=allowed,
|
|
291
|
+
)
|
|
292
|
+
if ctrl is None:
|
|
293
|
+
return None
|
|
294
|
+
if ctrl.selector:
|
|
295
|
+
return ctrl.selector
|
|
296
|
+
if ctrl.label and ctrl.tag in ("button", "a"):
|
|
297
|
+
return f"{ctrl.tag}:has-text({ctrl.label!r})"
|
|
298
|
+
return None
|
|
299
|
+
|
|
300
|
+
def run_and_heal(
|
|
301
|
+
self,
|
|
302
|
+
page: Any,
|
|
303
|
+
plan: Sequence[PlanStep],
|
|
304
|
+
*,
|
|
305
|
+
readback_oracle: Callable[[Any], bool],
|
|
306
|
+
) -> HealResult:
|
|
307
|
+
"""Execute plan, interactively healing any broken step on the live DOM."""
|
|
308
|
+
healed_plan: List[PlanStep] = []
|
|
309
|
+
healed_ids: List[str] = []
|
|
310
|
+
|
|
311
|
+
for step in plan:
|
|
312
|
+
try:
|
|
313
|
+
self._execute_step(page, step, step.selector)
|
|
314
|
+
healed_plan.append(step)
|
|
315
|
+
except Exception:
|
|
316
|
+
new_selector = self._heal_live_step(page, step)
|
|
317
|
+
if not new_selector:
|
|
318
|
+
return HealResult(
|
|
319
|
+
verified=False,
|
|
320
|
+
healed_steps=healed_ids,
|
|
321
|
+
healed_plan=healed_plan,
|
|
322
|
+
failure_reason=f"could_not_reground_step:{step.step_id}",
|
|
323
|
+
)
|
|
324
|
+
try:
|
|
325
|
+
self._execute_step(page, step, new_selector)
|
|
326
|
+
except Exception as exc:
|
|
327
|
+
return HealResult(
|
|
328
|
+
verified=False,
|
|
329
|
+
healed_steps=healed_ids,
|
|
330
|
+
healed_plan=healed_plan,
|
|
331
|
+
failure_reason=f"healed_selector_failed:{step.step_id}:{exc}",
|
|
332
|
+
)
|
|
333
|
+
healed_ids.append(step.step_id)
|
|
334
|
+
healed_plan.append(
|
|
335
|
+
PlanStep(
|
|
336
|
+
step_id=step.step_id,
|
|
337
|
+
action=step.action,
|
|
338
|
+
selector=new_selector,
|
|
339
|
+
semantic_label=step.semantic_label,
|
|
340
|
+
value=step.value,
|
|
341
|
+
is_commit=step.is_commit,
|
|
342
|
+
prefer_modal=step.prefer_modal,
|
|
343
|
+
)
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
if not readback_oracle(page):
|
|
347
|
+
return HealResult(
|
|
348
|
+
verified=False,
|
|
349
|
+
healed_steps=healed_ids,
|
|
350
|
+
healed_plan=healed_plan,
|
|
351
|
+
failure_reason="independent_readback_refuted_commit",
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
return HealResult(verified=True, healed_steps=healed_ids, healed_plan=healed_plan)
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Zero-dependency stdio JSON-RPC 2.0 MCP server for openadapt-kernel.
|
|
2
|
+
|
|
3
|
+
Exposes the kernel's core tools to any MCP client (Claude Desktop, Claude Code,
|
|
4
|
+
Cursor, or custom agent loops) without importing openadapt-flow:
|
|
5
|
+
- kernel_induce_pack
|
|
6
|
+
- kernel_qualify_offline
|
|
7
|
+
- kernel_run_pack (draft or verified autopilot)
|
|
8
|
+
- kernel_verify_receipt
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from dataclasses import asdict
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Dict, List, Optional, TextIO
|
|
19
|
+
|
|
20
|
+
from openadapt_kernel.copilot import qualify_verifier_offline, verify_receipt
|
|
21
|
+
from openadapt_kernel.extension_bridge import (
|
|
22
|
+
induce_pack_from_extension_recordings,
|
|
23
|
+
parse_extension_evidence_jsonl,
|
|
24
|
+
)
|
|
25
|
+
from openadapt_kernel.runner import run_portal_pack
|
|
26
|
+
|
|
27
|
+
SERVER_INFO = {"name": "openadapt-kernel", "version": "0.1.0"}
|
|
28
|
+
|
|
29
|
+
TOOLS_SPEC: List[Dict[str, Any]] = [
|
|
30
|
+
{
|
|
31
|
+
"name": "kernel_induce_pack",
|
|
32
|
+
"description": "Induce a zero-PII PortalPack from passive Chrome Co-Pilot extension_evidence.jsonl recordings.",
|
|
33
|
+
"inputSchema": {
|
|
34
|
+
"type": "object",
|
|
35
|
+
"properties": {
|
|
36
|
+
"pack_id": {"type": "string"},
|
|
37
|
+
"sessions": {
|
|
38
|
+
"type": "array",
|
|
39
|
+
"items": {
|
|
40
|
+
"type": "object",
|
|
41
|
+
"properties": {
|
|
42
|
+
"evidence_path": {"type": "string"},
|
|
43
|
+
"dossier": {"type": "object"},
|
|
44
|
+
},
|
|
45
|
+
"required": ["evidence_path", "dossier"],
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
"out_path": {"type": "string"},
|
|
49
|
+
},
|
|
50
|
+
"required": ["pack_id", "sessions", "out_path"],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"name": "kernel_qualify_offline",
|
|
55
|
+
"description": "Run the 4-mutant offline Plant-and-Catch qualification suite on a recorded trace (zero staging DB).",
|
|
56
|
+
"inputSchema": {
|
|
57
|
+
"type": "object",
|
|
58
|
+
"properties": {
|
|
59
|
+
"pack_path": {"type": "string"},
|
|
60
|
+
"evidence_path": {"type": "string"},
|
|
61
|
+
"pre_text": {"type": "string"},
|
|
62
|
+
},
|
|
63
|
+
"required": ["pack_path", "evidence_path"],
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"name": "kernel_run_pack",
|
|
68
|
+
"description": "Execute a PortalPack in draft (stop before submit) or verified autopilot mode with fresh-reload/cross-tab read-back.",
|
|
69
|
+
"inputSchema": {
|
|
70
|
+
"type": "object",
|
|
71
|
+
"properties": {
|
|
72
|
+
"pack_path": {"type": "string"},
|
|
73
|
+
"dossier": {"type": "object"},
|
|
74
|
+
"mode": {"type": "string", "enum": ["draft", "autopilot"]},
|
|
75
|
+
"url": {"type": "string"},
|
|
76
|
+
"cdp_url": {"type": "string"},
|
|
77
|
+
"commit_selector": {"type": "string"},
|
|
78
|
+
"private_key_path": {"type": "string"},
|
|
79
|
+
"receipt_out": {"type": "string"},
|
|
80
|
+
"episode_id": {"type": "string"},
|
|
81
|
+
},
|
|
82
|
+
"required": ["pack_path", "dossier"],
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
"name": "kernel_verify_receipt",
|
|
87
|
+
"description": "Verify an Ed25519-signed openadapt.kernel.receipt/v1 artifact offline.",
|
|
88
|
+
"inputSchema": {
|
|
89
|
+
"type": "object",
|
|
90
|
+
"properties": {
|
|
91
|
+
"receipt_path": {"type": "string"},
|
|
92
|
+
"public_key_path": {"type": "string"},
|
|
93
|
+
},
|
|
94
|
+
"required": ["receipt_path", "public_key_path"],
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _token_boundary_verifier(fields: Dict[str, str], text: str) -> bool:
|
|
101
|
+
compact = " ".join(text.split())
|
|
102
|
+
return all(
|
|
103
|
+
bool(re.search(rf"(?<!\w){re.escape(v)}(?!\w)", compact))
|
|
104
|
+
for v in fields.values()
|
|
105
|
+
if str(v).strip()
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def dispatch_tool_call(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
|
110
|
+
if name == "kernel_induce_pack":
|
|
111
|
+
sessions = [
|
|
112
|
+
(Path(s["evidence_path"]), dict(s["dossier"]), None)
|
|
113
|
+
for s in arguments["sessions"]
|
|
114
|
+
]
|
|
115
|
+
pack = induce_pack_from_extension_recordings(arguments["pack_id"], sessions)
|
|
116
|
+
out = Path(arguments["out_path"])
|
|
117
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
out.write_text(json.dumps(asdict(pack), indent=2), encoding="utf-8")
|
|
119
|
+
return {"ok": True, "pack": asdict(pack), "out_path": str(out)}
|
|
120
|
+
|
|
121
|
+
if name == "kernel_qualify_offline":
|
|
122
|
+
summary = parse_extension_evidence_jsonl(Path(arguments["evidence_path"]))
|
|
123
|
+
pre_text = arguments.get("pre_text") if arguments.get("pre_text") is not None else summary.pre_write_text
|
|
124
|
+
if not str(pre_text or "").strip():
|
|
125
|
+
raise ValueError(
|
|
126
|
+
"kernel_qualify_offline requires a captured pre-write DOM snapshot via pre_text or pre_write event"
|
|
127
|
+
)
|
|
128
|
+
pack_data = json.loads(Path(arguments["pack_path"]).read_text(encoding="utf-8"))
|
|
129
|
+
var_fields = list(pack_data.get("variable_fields") or summary.submitted_fields.keys())
|
|
130
|
+
expected = {k: summary.submitted_fields[k] for k in var_fields if k in summary.submitted_fields}
|
|
131
|
+
report = qualify_verifier_offline(
|
|
132
|
+
expected_fields=expected,
|
|
133
|
+
pre_write_text=str(pre_text),
|
|
134
|
+
post_write_text=summary.readback_text,
|
|
135
|
+
verifier_fn=_token_boundary_verifier,
|
|
136
|
+
)
|
|
137
|
+
return {"ok": report.qualified, "report": asdict(report)}
|
|
138
|
+
|
|
139
|
+
if name == "kernel_run_pack":
|
|
140
|
+
res = run_portal_pack(
|
|
141
|
+
pack_path=Path(arguments["pack_path"]),
|
|
142
|
+
dossier={str(k): str(v) for k, v in arguments["dossier"].items()},
|
|
143
|
+
mode=arguments.get("mode", "draft"),
|
|
144
|
+
url=arguments.get("url"),
|
|
145
|
+
cdp_url=arguments.get("cdp_url"),
|
|
146
|
+
commit_selector=arguments.get("commit_selector"),
|
|
147
|
+
private_key_path=Path(arguments["private_key_path"]) if arguments.get("private_key_path") else None,
|
|
148
|
+
receipt_out=Path(arguments["receipt_out"]) if arguments.get("receipt_out") else None,
|
|
149
|
+
episode_id=arguments.get("episode_id") or None,
|
|
150
|
+
headless=True,
|
|
151
|
+
)
|
|
152
|
+
return {"ok": res.outcome in ("READY_FOR_HUMAN_COMMIT", "VERIFIED"), "result": asdict(res)}
|
|
153
|
+
|
|
154
|
+
if name == "kernel_verify_receipt":
|
|
155
|
+
receipt = json.loads(Path(arguments["receipt_path"]).read_text(encoding="utf-8"))
|
|
156
|
+
pub_pem = Path(arguments["public_key_path"]).read_bytes()
|
|
157
|
+
valid = verify_receipt(receipt, pub_pem)
|
|
158
|
+
return {"ok": valid, "valid": valid, "outcome": receipt.get("payload", {}).get("outcome")}
|
|
159
|
+
|
|
160
|
+
raise ValueError(f"Unknown tool: {name}")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def handle_jsonrpc_message(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
164
|
+
req_id = msg.get("id")
|
|
165
|
+
method = str(msg.get("method") or "")
|
|
166
|
+
params = msg.get("params") or {}
|
|
167
|
+
|
|
168
|
+
if method == "notifications/initialized":
|
|
169
|
+
return None
|
|
170
|
+
if method == "initialize":
|
|
171
|
+
return {
|
|
172
|
+
"jsonrpc": "2.0",
|
|
173
|
+
"id": req_id,
|
|
174
|
+
"result": {
|
|
175
|
+
"protocolVersion": "2024-11-05",
|
|
176
|
+
"serverInfo": SERVER_INFO,
|
|
177
|
+
"capabilities": {"tools": {}},
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
if method == "tools/list":
|
|
181
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS_SPEC}}
|
|
182
|
+
if method == "tools/call":
|
|
183
|
+
try:
|
|
184
|
+
tool_name = str(params.get("name") or "")
|
|
185
|
+
tool_args = dict(params.get("arguments") or {})
|
|
186
|
+
payload = dispatch_tool_call(tool_name, tool_args)
|
|
187
|
+
return {
|
|
188
|
+
"jsonrpc": "2.0",
|
|
189
|
+
"id": req_id,
|
|
190
|
+
"result": {
|
|
191
|
+
"content": [{"type": "text", "text": json.dumps(payload)}],
|
|
192
|
+
"isError": not bool(payload.get("ok", False)),
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
except Exception as exc:
|
|
196
|
+
return {
|
|
197
|
+
"jsonrpc": "2.0",
|
|
198
|
+
"id": req_id,
|
|
199
|
+
"result": {
|
|
200
|
+
"content": [{"type": "text", "text": json.dumps({"ok": False, "error": str(exc)})}],
|
|
201
|
+
"isError": True,
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
"jsonrpc": "2.0",
|
|
206
|
+
"id": req_id,
|
|
207
|
+
"error": {"code": -32601, "message": f"Method not found: {method}"},
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def serve_stdio(stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout) -> None:
|
|
212
|
+
"""Line-delimited JSON-RPC 2.0 stdio loop."""
|
|
213
|
+
for raw in stdin:
|
|
214
|
+
line = raw.strip()
|
|
215
|
+
if not line:
|
|
216
|
+
continue
|
|
217
|
+
try:
|
|
218
|
+
msg = json.loads(line)
|
|
219
|
+
reply = handle_jsonrpc_message(msg)
|
|
220
|
+
except Exception as exc:
|
|
221
|
+
reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}
|
|
222
|
+
if reply is not None:
|
|
223
|
+
stdout.write(json.dumps(reply) + "\n")
|
|
224
|
+
stdout.flush()
|