@0perator/operator 0.1.360-next.2 → 0.2.1
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/README.md +5 -4
- package/dist/auth/commands.js +7 -3
- package/dist/auth/identity.js +1 -0
- package/dist/auth/staff.js +55 -0
- package/dist/autonomy/delegate-mode.js +159 -0
- package/dist/autonomy/delegate.js +42 -15
- package/dist/autonomy/headless.js +7 -4
- package/dist/autonomy/index.js +2 -4
- package/dist/autonomy/session-factory.js +13 -12
- package/dist/autonomy/subagent-model.js +17 -7
- package/dist/background/capacity.js +136 -0
- package/dist/background/evidence.js +42 -0
- package/dist/background/index.js +336 -45
- package/dist/background/lane-phase.js +60 -0
- package/dist/background/lane-summary.js +151 -0
- package/dist/background/notices.js +12 -3
- package/dist/background/resume.js +125 -0
- package/dist/background/synthesis.js +25 -0
- package/dist/browser/engine.js +163 -0
- package/dist/browser/session.js +130 -140
- package/dist/bus/inbox.js +150 -6
- package/dist/cli.js +343 -86
- package/dist/config/features.js +3 -3
- package/dist/config/persona.js +29 -3
- package/dist/config/settings.js +262 -21
- package/dist/config/staff-prompt.js +12 -0
- package/dist/engine/agent.js +52 -41
- package/dist/engine/aurora.js +40 -8
- package/dist/engine/batch-scheduler.js +4 -13
- package/dist/engine/compaction.js +2 -2
- package/dist/engine/continuation.js +30 -32
- package/dist/engine/decision-points.js +2 -3
- package/dist/engine/fanout.js +16 -0
- package/dist/engine/loop-guard.js +26 -83
- package/dist/engine/messages.js +2 -2
- package/dist/engine/moa.js +18 -2
- package/dist/engine/native-vision-node.js +72 -0
- package/dist/engine/native-vision.js +103 -0
- package/dist/engine/selfheal.js +1 -1
- package/dist/engine/toolcalls.js +6 -6
- package/dist/engine/verify-gate.js +37 -7
- package/dist/gateway-cli.js +14 -3
- package/dist/index.js +3 -0
- package/dist/mcp/phone-server.js +30 -0
- package/dist/memory/live-progress.js +4 -5
- package/dist/moa/codeact-lane.js +98 -0
- package/dist/moa/codeact-sandbox.js +409 -0
- package/dist/moa/codeact.js +140 -0
- package/dist/permissions/artifact-visibility.js +10 -0
- package/dist/permissions/index.js +33 -17
- package/dist/permissions/signature.js +5 -0
- package/dist/permissions/tier.js +4 -2
- package/dist/phone-cli.js +65 -0
- package/dist/products/craft.js +2 -2
- package/dist/remote/grants.js +119 -0
- package/dist/remote/host.js +63 -6
- package/dist/router/models.js +29 -29
- package/dist/selfimprove/index.js +9 -7
- package/dist/services/preflight.js +35 -91
- package/dist/session.js +173 -46
- package/dist/skills/install-guard.js +68 -0
- package/dist/skills/install.js +67 -0
- package/dist/toolchain/manifest.json +13 -13
- package/dist/tools/background-result.js +1 -1
- package/dist/tools/classes.js +103 -0
- package/dist/tools/contract.js +1 -1
- package/dist/tools/craft.js +13 -2
- package/dist/tools/deferred.js +1 -0
- package/dist/tools/device/android.js +227 -0
- package/dist/tools/device/classify.js +127 -0
- package/dist/tools/device/deps.js +69 -0
- package/dist/tools/device/desktop.js +82 -0
- package/dist/tools/device/harness.js +262 -0
- package/dist/tools/device/iphone.js +206 -0
- package/dist/tools/device/mirroring-jxa.js +146 -0
- package/dist/tools/device/setup.js +90 -0
- package/dist/tools/device/tools.js +70 -0
- package/dist/tools/device/types.js +19 -0
- package/dist/tools/executor.js +25 -15
- package/dist/tools/generation-gateway.js +94 -0
- package/dist/tools/registry.js +95 -155
- package/dist/ui/App.js +18 -6
- package/dist/ui/ApprovalPrompt.js +10 -4
- package/dist/ui/BgPanel.js +17 -12
- package/dist/ui/Header.js +1 -6
- package/dist/ui/StatusRule.js +18 -7
- package/dist/ui/ToolStep.js +3 -3
- package/dist/ui/Transcript.js +36 -14
- package/dist/ui/UpdatePrompt.js +40 -0
- package/dist/ui/batchLine.js +4 -4
- package/dist/ui/editdiff.js +2 -4
- package/dist/ui/format.js +4 -20
- package/dist/ui/liveTools.js +3 -3
- package/dist/ui/modelPicker.js +1 -1
- package/dist/ui/opsMode.js +20 -0
- package/dist/ui/slashCommands.js +1 -0
- package/dist/ui/types.js +0 -2
- package/dist/update-check.js +145 -0
- package/dist/update.js +59 -15
- package/dist/util/slash.js +2 -2
- package/package.json +4 -2
- package/src/tools/device/NOTICE +37 -0
- package/dist/browser/cdp.js +0 -271
- package/dist/tools/mutating.js +0 -15
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The iPhone Mirroring driver for a Mac without Chauffeur: one JavaScript-for-Automation program run by the system's
|
|
2
|
+
// own `osascript -l JavaScript` (on every Mac — nothing to install), reaching CoreGraphics, AppKit, Accessibility and
|
|
3
|
+
// Vision through the ObjC bridge. It is a port of phone-harness's mirror.py and ocr.py (MIT, see ./NOTICE). The
|
|
4
|
+
// program is fixed text; every value (coordinates, the text to paste, the image path) arrives as an argv word and is
|
|
5
|
+
// read as data, so nothing the model sends is ever evaluated. It never asks macOS for a permission: AXIsProcessTrusted
|
|
6
|
+
// and CGPreflightScreenCaptureAccess only read the grant, they raise no dialog.
|
|
7
|
+
//
|
|
8
|
+
// What phone-harness learned the hard way and this keeps: windows are matched by the owner pid of the
|
|
9
|
+
// com.apple.ScreenContinuity process, never the (localized) app name; iPhone Mirroring forwards raw HID keycodes to iOS
|
|
10
|
+
// and drops the CGEvent flag mask, so a modifier is a key held down, not a flag set; text goes in by paste (immune to
|
|
11
|
+
// autocorrect and keyboard layout), keystrokes only on request; the live phone image is a video stream accessibility
|
|
12
|
+
// cannot see into, so a window with accessible labels or buttons is an interstitial (paused, iPhone in Use, Connect).
|
|
13
|
+
export const MIRRORING_BUNDLE = "com.apple.ScreenContinuity";
|
|
14
|
+
export const MIRRORING_APP = "/System/Applications/iPhone Mirroring.app";
|
|
15
|
+
export const MIRRORING_JXA = `
|
|
16
|
+
ObjC.import('AppKit'); ObjC.import('CoreGraphics'); ObjC.import('ApplicationServices');
|
|
17
|
+
var BUNDLE = 'com.apple.ScreenContinuity';
|
|
18
|
+
function out(o) { return JSON.stringify(o); }
|
|
19
|
+
function app() { var a = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(BUNDLE); return a.count > 0 ? a.objectAtIndex(0) : null; }
|
|
20
|
+
function win(pid) {
|
|
21
|
+
var list = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(1, 0))) || [];
|
|
22
|
+
for (var i = 0; i < list.length; i++) {
|
|
23
|
+
var w = list[i];
|
|
24
|
+
if (w.kCGWindowOwnerPID === pid && (w.kCGWindowLayer || 0) === 0) {
|
|
25
|
+
var b = w.kCGWindowBounds; return { x: b.X, y: b.Y, w: b.Width, h: b.Height, id: w.kCGWindowNumber };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
function front(pid) { var f = $.NSWorkspace.sharedWorkspace.frontmostApplication; return !!f && f.processIdentifier === pid; }
|
|
31
|
+
function activate() {
|
|
32
|
+
var a = app(); if (!a) throw new Error('iPhone Mirroring is not running');
|
|
33
|
+
for (var i = 0; i < 25 && !front(a.processIdentifier); i++) { a.activateWithOptions(2); delay(0.08); }
|
|
34
|
+
if (!front(a.processIdentifier)) throw new Error('could not bring iPhone Mirroring to the front, so nothing was sent');
|
|
35
|
+
return a;
|
|
36
|
+
}
|
|
37
|
+
function mouse(type, x, y) { $.CGEventPost(0, $.CGEventCreateMouseEvent($(), type, { x: x, y: y }, 0)); }
|
|
38
|
+
var MODS = { cmd: [55, 0x100000], shift: [56, 0x20000], alt: [58, 0x80000], option: [58, 0x80000], ctrl: [59, 0x40000] };
|
|
39
|
+
function keyEv(code, down, flags) { var e = $.CGEventCreateKeyboardEvent($(), code, down); if (flags) $.CGEventSetFlags(e, flags); $.CGEventPost(0, e); }
|
|
40
|
+
function chord(mods, code) {
|
|
41
|
+
var acc = 0;
|
|
42
|
+
mods.forEach(function (m) { acc |= MODS[m][1]; keyEv(MODS[m][0], true, acc); delay(0.01); });
|
|
43
|
+
try { keyEv(code, true, acc); delay(0.03); keyEv(code, false, acc); delay(0.03); }
|
|
44
|
+
finally { mods.slice().reverse().forEach(function (m) { acc &= ~MODS[m][1]; keyEv(MODS[m][0], false, acc); delay(0.01); }); }
|
|
45
|
+
}
|
|
46
|
+
function axTexts(pid) {
|
|
47
|
+
var texts = [], buttons = [];
|
|
48
|
+
function attr(el, name) { var r = Ref(); return $.AXUIElementCopyAttributeValue(el, $(name), r) === 0 ? ObjC.castRefToObject(r[0]) : null; }
|
|
49
|
+
function str(v) { try { return v ? ObjC.unwrap(v) : ''; } catch (e) { return ''; } }
|
|
50
|
+
function walk(el, depth) {
|
|
51
|
+
if (depth > 8) return;
|
|
52
|
+
var role = str(attr(el, 'AXRole')), label = str(attr(el, 'AXValue')) || str(attr(el, 'AXTitle')) || str(attr(el, 'AXDescription'));
|
|
53
|
+
if (typeof label === 'string' && label.trim()) { if (role === 'AXButton') buttons.push(label.trim()); else if (role === 'AXStaticText') texts.push(label.trim()); }
|
|
54
|
+
var kids = attr(el, 'AXChildren'); if (!kids) return;
|
|
55
|
+
for (var i = 0; i < kids.count; i++) walk(kids.objectAtIndex(i), depth + 1);
|
|
56
|
+
}
|
|
57
|
+
var wins = attr($.AXUIElementCreateApplication(pid), 'AXWindows');
|
|
58
|
+
if (!wins || wins.count === 0) return { ok: false };
|
|
59
|
+
walk(wins.objectAtIndex(0), 0);
|
|
60
|
+
return { ok: true, texts: texts, buttons: buttons };
|
|
61
|
+
}
|
|
62
|
+
function run(argv) {
|
|
63
|
+
var verb = argv[0], n = function (i) { var v = Number(argv[i]); if (!isFinite(v)) throw new Error('bad number: ' + argv[i]); return v; };
|
|
64
|
+
if (verb === 'perms') { ObjC.bindFunction('CGPreflightScreenCaptureAccess', ['bool', []]); return out({ accessibility: !!$.AXIsProcessTrusted(), screenRecording: !!$.CGPreflightScreenCaptureAccess() }); }
|
|
65
|
+
if (verb === 'window') {
|
|
66
|
+
var a = app(); if (!a) return out({ running: false });
|
|
67
|
+
var pid = a.processIdentifier, ax = null;
|
|
68
|
+
if ($.AXIsProcessTrusted()) { try { ax = axTexts(pid); } catch (e) { ax = { ok: false }; } }
|
|
69
|
+
return out({ running: true, pid: pid, window: win(pid), front: front(pid), ax: ax });
|
|
70
|
+
}
|
|
71
|
+
if (verb === 'activate') { activate(); return out({ ok: true }); }
|
|
72
|
+
if (verb === 'tap') {
|
|
73
|
+
activate(); var x = n(1), y = n(2), hold = argv[3] ? n(3) : 0.06;
|
|
74
|
+
mouse(5, x, y); delay(0.1); mouse(1, x, y); delay(hold); mouse(2, x, y); return out({ ok: true });
|
|
75
|
+
}
|
|
76
|
+
if (verb === 'drag') {
|
|
77
|
+
activate(); var x1 = n(1), y1 = n(2), x2 = n(3), y2 = n(4), secs = n(5), steps = 14;
|
|
78
|
+
mouse(5, x1, y1); delay(0.1); mouse(1, x1, y1);
|
|
79
|
+
for (var i = 1; i <= steps; i++) { var t = i / steps; mouse(6, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t); delay(secs / steps); }
|
|
80
|
+
mouse(2, x2, y2); return out({ ok: true });
|
|
81
|
+
}
|
|
82
|
+
if (verb === 'scroll') {
|
|
83
|
+
activate(); var sx = n(1), sy = n(2), dy = n(3), dx = n(4), k = 6;
|
|
84
|
+
mouse(5, sx, sy); delay(0.1);
|
|
85
|
+
for (var j = 0; j < k; j++) { var e = $.CGEventCreateScrollWheelEvent2($(), 0, 2, Math.round(dy / k), Math.round(dx / k), 0); $.CGEventSetLocation(e, { x: sx, y: sy }); $.CGEventPost(0, e); delay(0.03); }
|
|
86
|
+
return out({ ok: true });
|
|
87
|
+
}
|
|
88
|
+
if (verb === 'key') { activate(); var parts = argv[1].split('+'); chord(parts.slice(0, -1), n(2)); return out({ ok: true }); }
|
|
89
|
+
if (verb === 'keycodes') {
|
|
90
|
+
activate(); var codes = JSON.parse(argv[1]);
|
|
91
|
+
codes.forEach(function (c) { chord(c[1] ? ['shift'] : [], c[0]); delay(0.03); });
|
|
92
|
+
return out({ ok: true });
|
|
93
|
+
}
|
|
94
|
+
if (verb === 'paste') {
|
|
95
|
+
var pb = $.NSPasteboard.generalPasteboard; pb.clearContents; pb.setStringForType($(argv[1]), $.NSPasteboardTypeString);
|
|
96
|
+
if (ObjC.unwrap(pb.stringForType($.NSPasteboardTypeString)) !== argv[1]) throw new Error('the clipboard did not take the text, so nothing was pasted');
|
|
97
|
+
activate(); delay(0.15); chord(['cmd'], 9); return out({ ok: true });
|
|
98
|
+
}
|
|
99
|
+
if (verb === 'ocr') {
|
|
100
|
+
ObjC.import('Vision');
|
|
101
|
+
var handler = $.VNImageRequestHandler.alloc.initWithURLOptions($.NSURL.fileURLWithPath(argv[1]), $());
|
|
102
|
+
var req = $.VNRecognizeTextRequest.alloc.init; req.recognitionLevel = 0;
|
|
103
|
+
if (!handler.performRequestsError($.NSArray.arrayWithObject(req), $())) throw new Error('Vision text recognition failed');
|
|
104
|
+
var res = req.results, items = [];
|
|
105
|
+
for (var r = 0; r < res.count; r++) {
|
|
106
|
+
var obs = res.objectAtIndex(r), c = obs.topCandidates(1); if (c.count === 0) continue;
|
|
107
|
+
var bb = obs.boundingBox, best = c.objectAtIndex(0);
|
|
108
|
+
items.push({ text: ObjC.unwrap(best.string), confidence: best.confidence, x: bb.origin.x, y: bb.origin.y, w: bb.size.width, h: bb.size.height });
|
|
109
|
+
}
|
|
110
|
+
return out({ items: items });
|
|
111
|
+
}
|
|
112
|
+
throw new Error('unknown verb ' + verb);
|
|
113
|
+
}
|
|
114
|
+
`;
|
|
115
|
+
// US-layout virtual keycodes (mirror.py _KEYCODES / _PUNCT_KEYCODES / _SHIFTED), for keystroke typing and named keys.
|
|
116
|
+
const BASE = {
|
|
117
|
+
a: 0, s: 1, d: 2, f: 3, h: 4, g: 5, z: 6, x: 7, c: 8, v: 9, b: 11, q: 12, w: 13, e: 14, r: 15, y: 16, t: 17, o: 31, u: 32,
|
|
118
|
+
i: 34, p: 35, l: 37, j: 38, k: 40, n: 45, m: 46, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26, "8": 28,
|
|
119
|
+
"9": 25, "0": 29, ".": 47, ",": 43, "/": 44, ";": 41, "'": 39, "[": 33, "]": 30, "\\": 42, "-": 27, "=": 24, "`": 50, " ": 49,
|
|
120
|
+
};
|
|
121
|
+
const SHIFTED = {
|
|
122
|
+
"!": "1", "@": "2", "#": "3", $: "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0", _: "-", "+": "=", ":": ";",
|
|
123
|
+
'"': "'", "<": ",", ">": ".", "?": "/", "~": "`", "{": "[", "}": "]", "|": "\\",
|
|
124
|
+
};
|
|
125
|
+
export const NAMED_KEYCODES = {
|
|
126
|
+
return: 36, enter: 36, tab: 48, space: 49, delete: 51, escape: 53, left: 123, right: 124, down: 125, up: 126,
|
|
127
|
+
...BASE,
|
|
128
|
+
};
|
|
129
|
+
/** Each character → [keycode, needs shift]; null when a character has no US-layout key (emoji, accents). */
|
|
130
|
+
export function keycodesFor(text) {
|
|
131
|
+
const out = [];
|
|
132
|
+
for (const ch of text) {
|
|
133
|
+
if (ch === "\n") {
|
|
134
|
+
out.push([36, false]);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const lower = ch.toLowerCase();
|
|
138
|
+
const upper = ch !== lower;
|
|
139
|
+
const base = SHIFTED[ch] ?? lower;
|
|
140
|
+
const code = BASE[base];
|
|
141
|
+
if (code === undefined)
|
|
142
|
+
return null;
|
|
143
|
+
out.push([code, upper || ch in SHIFTED]);
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// `operator phone setup` and phone_status: scan every backend this OS has, print a checklist (✓ done, ✗ the step that
|
|
2
|
+
// is missing, · not reached yet, – not available on this OS) and the ONE next action. It only reads: no app is opened,
|
|
3
|
+
// no permission is requested (macOS never shows a dialog for it), nothing is tapped. The optional last step — one
|
|
4
|
+
// screenshot and a vision description — runs only when the owner says yes.
|
|
5
|
+
import { deviceDeps } from "./deps.js";
|
|
6
|
+
import { osName } from "./desktop.js";
|
|
7
|
+
import { scanDevices, phoneScreenshot } from "./harness.js";
|
|
8
|
+
const failure = (s) => (s.fix ? `${s.detail} → ${s.fix}` : s.detail);
|
|
9
|
+
function ladder(steps, failedAt, failText) {
|
|
10
|
+
return steps.map((text, i) => i < failedAt ? { mark: "✓", text } : i === failedAt ? { mark: "✗", text: failText ? `${text} — ${failText}` : text } : { mark: "·", text });
|
|
11
|
+
}
|
|
12
|
+
function androidItems(s) {
|
|
13
|
+
const steps = ["adb installed", "phone plugged in (USB debugging on)", "this computer allowed on the phone", "phone unlocked"];
|
|
14
|
+
const at = { "missing-tool": 0, "no-device": 1, unauthorized: 2, offline: 2, locked: 3, ready: 4, unreachable: 0 };
|
|
15
|
+
const items = ladder(steps, at[s.state] ?? 0, s.state === "ready" ? undefined : failure(s));
|
|
16
|
+
if (s.state === "ready")
|
|
17
|
+
items.push({ mark: "✓", text: s.detail });
|
|
18
|
+
return items;
|
|
19
|
+
}
|
|
20
|
+
function iphoneItems(s) {
|
|
21
|
+
if (s.state === "unsupported" && !/macOS \d/.test(s.detail))
|
|
22
|
+
return [{ mark: "–", text: s.detail }];
|
|
23
|
+
const steps = ["macOS 15 or later", "iPhone Mirroring app present", "Accessibility permission", "Screen Recording permission", "iPhone Mirroring open", "iPhone paired", "mirroring session live"];
|
|
24
|
+
let at = 7;
|
|
25
|
+
if (s.state === "unsupported")
|
|
26
|
+
at = 0;
|
|
27
|
+
else if (s.state === "missing-tool")
|
|
28
|
+
at = 1;
|
|
29
|
+
else if (s.state === "permission")
|
|
30
|
+
at = /Accessibility/.test(s.detail) ? 2 : 3;
|
|
31
|
+
else if (s.state === "not-running")
|
|
32
|
+
at = 4;
|
|
33
|
+
else if (s.state === "not-paired")
|
|
34
|
+
at = 5;
|
|
35
|
+
else if (s.state === "blocked" || s.state === "unreachable")
|
|
36
|
+
at = 6;
|
|
37
|
+
const items = ladder(steps, at, s.state === "ready" ? undefined : failure(s));
|
|
38
|
+
if (s.state === "ready")
|
|
39
|
+
items.push({ mark: "✓", text: s.detail });
|
|
40
|
+
return items;
|
|
41
|
+
}
|
|
42
|
+
function desktopItems(s) {
|
|
43
|
+
if (s.state === "unsupported")
|
|
44
|
+
return [{ mark: "–", text: s.detail }];
|
|
45
|
+
return [{ mark: s.state === "ready" ? "✓" : "✗", text: s.state === "ready" ? "Chauffeur reachable (this Mac)" : `Chauffeur reachable — ${failure(s)}` }];
|
|
46
|
+
}
|
|
47
|
+
// How far along a backend got, to pick the next action from the one closest to working.
|
|
48
|
+
const PROGRESS = { "missing-tool": 1, "no-device": 2, unauthorized: 3, offline: 3, permission: 3, "not-running": 4, "not-paired": 5, locked: 6, blocked: 6 };
|
|
49
|
+
export async function setupReport() {
|
|
50
|
+
const statuses = await scanDevices();
|
|
51
|
+
const by = (k) => statuses.find((s) => s.kind === k);
|
|
52
|
+
const sections = [
|
|
53
|
+
{ title: "Android (adb)", items: androidItems(by("android")) },
|
|
54
|
+
{ title: "iPhone (iPhone Mirroring)", items: iphoneItems(by("iphone")) },
|
|
55
|
+
{ title: `Desktop (${osName(deviceDeps().platform)})`, items: desktopItems(by("desktop")) },
|
|
56
|
+
];
|
|
57
|
+
const ready = statuses.filter((s) => s.state === "ready" && s.kind !== "desktop").map((s) => s.kind);
|
|
58
|
+
let next;
|
|
59
|
+
if (ready.length)
|
|
60
|
+
next = `ready: ${ready.join(" and ")}. Optional last step: one screenshot + a description to confirm Operator sees the phone.`;
|
|
61
|
+
else {
|
|
62
|
+
const phones = statuses.filter((s) => s.kind !== "desktop" && s.fix && s.state !== "unsupported");
|
|
63
|
+
const best = phones.sort((a, b) => (PROGRESS[b.state] ?? 0) - (PROGRESS[a.state] ?? 0))[0];
|
|
64
|
+
next = best ? `${best.kind}: ${best.fix}` : "plug in an Android phone with USB debugging on, or open iPhone Mirroring on a Mac with macOS 15+";
|
|
65
|
+
}
|
|
66
|
+
return { os: osName(deviceDeps().platform), sections, next, ready, statuses };
|
|
67
|
+
}
|
|
68
|
+
export function renderSetup(r) {
|
|
69
|
+
const lines = [`Phone setup — ${r.os}`, ""];
|
|
70
|
+
for (const s of r.sections) {
|
|
71
|
+
lines.push(s.title);
|
|
72
|
+
for (const i of s.items)
|
|
73
|
+
lines.push(` ${i.mark} ${i.text}`);
|
|
74
|
+
lines.push("");
|
|
75
|
+
}
|
|
76
|
+
lines.push(`Next: ${r.next}`);
|
|
77
|
+
return lines.join("\n");
|
|
78
|
+
}
|
|
79
|
+
/** The harmless read-only check: one screenshot of the ready phone and what vision sees on it. */
|
|
80
|
+
export async function readOnlyCheck(device) {
|
|
81
|
+
return phoneScreenshot({ ...(device ? { device } : {}), describe: true });
|
|
82
|
+
}
|
|
83
|
+
/** phone_status: the same checklist; `check: true` adds the read-only screenshot + description (the caller confirmed). */
|
|
84
|
+
export async function phoneStatus(args) {
|
|
85
|
+
const r = await setupReport();
|
|
86
|
+
const text = renderSetup(r);
|
|
87
|
+
if (args.check !== true || !r.ready.length)
|
|
88
|
+
return text;
|
|
89
|
+
return `${text}\n\n--- read-only check ---\n${await readOnlyCheck(typeof args.device === "string" ? args.device : undefined)}`;
|
|
90
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { phoneKey, phoneOpenApp, phoneRead, phoneScreenshot, phoneSwipe, phoneTap, phoneType } from "./harness.js";
|
|
2
|
+
import { phoneStatus } from "./setup.js";
|
|
3
|
+
import { DEVICE_KEYS } from "./types.js";
|
|
4
|
+
const BINS = ["adb", "osascript", "screencapture", "chauffeur-local", "chauffeur", "sh"];
|
|
5
|
+
const device = { type: "string", description: 'iphone | android | desktop | an adb serial; default: the one phone that is ready' };
|
|
6
|
+
const intent = { type: "string", enum: ["spend", "send", "account"], description: "declare it when the step pays, sends or changes an account: the owner is asked with a screenshot" };
|
|
7
|
+
const verify = { type: "boolean", description: "default true: a screenshot after the action (its path is returned)" };
|
|
8
|
+
const describe = { type: "boolean", description: "also describe the after screenshot with vision" };
|
|
9
|
+
const ACTION = { v: 1, effects: ["device"], bins: BINS, audit: ["device", "x", "y", "key", "name", "direction"] };
|
|
10
|
+
export const PHONE_TOOLS = [
|
|
11
|
+
{
|
|
12
|
+
name: "phone_status",
|
|
13
|
+
contract: { v: 1, effects: ["read", "device"], bins: [...BINS, "sw_vers"] },
|
|
14
|
+
description: "Setup checklist: which phones and screens Operator can drive here (iPhone via iPhone Mirroring, Android via adb, this desktop), what is done, what is missing, and the one next action.",
|
|
15
|
+
parameters: { type: "object", properties: { check: { type: "boolean", description: "also take one screenshot and describe it (read-only); only after the owner said yes" }, device } },
|
|
16
|
+
run: phoneStatus,
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
name: "phone_screenshot",
|
|
20
|
+
contract: { v: 1, effects: ["device", "write"], bins: BINS },
|
|
21
|
+
description: "Screenshot the phone (or desktop): returns the PNG path and its pixel size. Coordinates for phone_tap and phone_swipe are pixels in this image. describe: true adds a vision description.",
|
|
22
|
+
parameters: { type: "object", properties: { device, describe: { type: "boolean" }, question: { type: "string", description: "what to ask vision about the screen" } } },
|
|
23
|
+
run: phoneScreenshot,
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: "phone_read",
|
|
27
|
+
contract: { v: 1, effects: ["device", "write"], bins: BINS },
|
|
28
|
+
description: "Read the text on the phone screen with positions: Android's accessibility tree, the iPhone window's OCR, Chauffeur on the desktop; vision when none can read it.",
|
|
29
|
+
parameters: { type: "object", properties: { device, vision: { type: "boolean", description: "default true: fall back to vision when no text is readable" } } },
|
|
30
|
+
run: phoneRead,
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
name: "phone_tap",
|
|
34
|
+
contract: ACTION,
|
|
35
|
+
description: "Tap on the phone: by x, y (pixels in the latest phone_screenshot) or by the visible text of a button. Screenshot after by default.",
|
|
36
|
+
parameters: { type: "object", properties: { device, x: { type: "number" }, y: { type: "number" }, text: { type: "string", description: "visible label to tap instead of x, y" }, intent, verify, describe } },
|
|
37
|
+
run: phoneTap,
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: "phone_type",
|
|
41
|
+
contract: ACTION,
|
|
42
|
+
description: "Type text into the focused field on the phone (iPhone: pasted, exact; Android: ASCII). submit: true presses enter after it. Tap the field first.",
|
|
43
|
+
parameters: { type: "object", properties: { device, text: { type: "string" }, submit: { type: "boolean" }, keystrokes: { type: "boolean", description: "iPhone: real key presses instead of paste (US layout, autocorrect applies)" }, intent, verify, describe }, required: ["text"] },
|
|
44
|
+
run: phoneType,
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: "phone_swipe",
|
|
48
|
+
contract: ACTION,
|
|
49
|
+
description: "Swipe on the phone: direction up/down/left/right (\"up\" scrolls to content further down), or x1, y1 → x2, y2 in screenshot pixels.",
|
|
50
|
+
parameters: { type: "object", properties: { device, direction: { type: "string", enum: ["up", "down", "left", "right"] }, x1: { type: "number" }, y1: { type: "number" }, x2: { type: "number" }, y2: { type: "number" }, duration_ms: { type: "number" }, text: { type: "string", description: "the control it slides, e.g. \"slide to pay\"" }, intent, verify, describe } },
|
|
51
|
+
run: phoneSwipe,
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: "phone_key",
|
|
55
|
+
contract: ACTION,
|
|
56
|
+
description: "Press a key on the phone: home, back (Android only), recents, enter, delete, volume, … iPhone home/recents/search are Mirroring's Cmd+1/2/3.",
|
|
57
|
+
parameters: { type: "object", properties: { device, key: { type: "string", enum: [...DEVICE_KEYS] }, intent, verify, describe }, required: ["key"] },
|
|
58
|
+
run: phoneKey,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: "phone_open_app",
|
|
62
|
+
contract: ACTION,
|
|
63
|
+
description: "Open an app on the phone by name (\"Settings\", \"Maps\"); on Android a package id works too. iPhone opens it through Spotlight.",
|
|
64
|
+
parameters: { type: "object", properties: { device, name: { type: "string" }, verify, describe }, required: ["name"] },
|
|
65
|
+
run: phoneOpenApp,
|
|
66
|
+
},
|
|
67
|
+
];
|
|
68
|
+
export const PHONE_TOOL_NAMES = PHONE_TOOLS.map((t) => t.name);
|
|
69
|
+
/** The tools that act (and ask outside Autonomous mode); the reads run unprompted like chauffeur's reads. */
|
|
70
|
+
export const PHONE_ACTION_NAMES = ["phone_tap", "phone_type", "phone_swipe", "phone_key", "phone_open_app"];
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// One interface for every screen Operator drives: the macOS desktop, an iPhone through iPhone Mirroring, an Android
|
|
2
|
+
// phone over adb, and the Windows / Linux desktops still to come. A backend owns everything platform-specific; the
|
|
3
|
+
// tools, the permission gate, the audit trail and the skill are shared (harness.ts, tools.ts). Coordinates are always
|
|
4
|
+
// in the pixels of the backend's latest screenshot, the image the model looked at.
|
|
5
|
+
/** Keys a phone or desktop understands by name. Not every backend has every key (iOS has no Back). */
|
|
6
|
+
export const DEVICE_KEYS = ["home", "back", "recents", "enter", "delete", "tab", "space", "escape", "up", "down", "left",
|
|
7
|
+
"right", "volume_up", "volume_down", "power", "search", "menu"];
|
|
8
|
+
export class Unsupported extends Error {
|
|
9
|
+
constructor(message) { super(message); this.name = "Unsupported"; }
|
|
10
|
+
}
|
|
11
|
+
/** A device the owner has to act on before Operator can (plug in, unlock, tap Allow, grant a permission). */
|
|
12
|
+
export class NeedsOwner extends Error {
|
|
13
|
+
fix;
|
|
14
|
+
constructor(message, fix) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.fix = fix;
|
|
17
|
+
this.name = "NeedsOwner";
|
|
18
|
+
}
|
|
19
|
+
}
|
package/dist/tools/executor.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// new user turn (not required by SPEC §3's
|
|
9
9
|
// round loop itself, but needed so the guard
|
|
10
10
|
// doesn't bleed across turns)
|
|
11
|
-
import {
|
|
11
|
+
import { CWD_DEFAULTED, DIR_DEFAULTED, IDEMPOTENT, POLLERS, SHELL_FOREGROUND, WORKSPACE_DEFAULTED, mutationLanded } from "./classes.js";
|
|
12
12
|
import { isAbsolute, join, resolve } from "node:path";
|
|
13
13
|
import { registry } from "./registry.js";
|
|
14
14
|
import { expandPath } from "./paths.js";
|
|
@@ -18,15 +18,11 @@ import { shellKeyStore, shellExecMode, shellSignalStore } from "./shell-context.
|
|
|
18
18
|
import { capToolResult } from "./result-cap.js";
|
|
19
19
|
import { spillToolOutput } from "./tool-output-spill.js"; // GW-10: lossless eviction — spill big outputs, hand back a re-readable pointer
|
|
20
20
|
import { semanticCompress } from "./semantic-compress.js";
|
|
21
|
+
import { allowSandboxWriteRoot } from "./sandbox.js";
|
|
21
22
|
export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
|
|
22
23
|
import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
|
|
23
|
-
// Command tools whose working directory should default to the executor root (they take an optional `cwd`).
|
|
24
|
-
const CWD_TOOLS = new Set(["bash", "shell_exec", "shell_background", "git", "git_command", "git_status"]);
|
|
25
24
|
// Args that name a filesystem path the file tools read/write; a RELATIVE one is resolved under the root.
|
|
26
25
|
const PATH_ARGS = ["path", "file", "filename", "workspace"];
|
|
27
|
-
// Tools that take an optional `workspace` and otherwise fall back to process.cwd() — a rooted session must
|
|
28
|
-
// default it to its own root or the call lands in whatever directory the host process happens to run in.
|
|
29
|
-
const WORKSPACE_TOOLS = new Set(["checkpoint"]);
|
|
30
26
|
// BTX conflict keys must be the ABSOLUTE path a call will really touch, or "d.txt", "./d.txt", "/cwd/d.txt" and
|
|
31
27
|
// "~/d.txt" each look like a different resource and a batched write+read of one file races. Only path-named args
|
|
32
28
|
// are resolved (array elements and nested objects included, by the arg name they sit under); a url, or an id
|
|
@@ -46,15 +42,15 @@ export function rootArgs(name, args, root) {
|
|
|
46
42
|
}
|
|
47
43
|
if (typeof a.cwd === "string" && a.cwd && !isAbsolute(a.cwd) && !a.cwd.startsWith("~"))
|
|
48
44
|
a.cwd = join(root, a.cwd);
|
|
49
|
-
else if (a.cwd == null &&
|
|
45
|
+
else if (a.cwd == null && CWD_DEFAULTED.has(name))
|
|
50
46
|
a.cwd = root;
|
|
51
|
-
if (a.workspace == null &&
|
|
47
|
+
if (a.workspace == null && WORKSPACE_DEFAULTED.has(name))
|
|
52
48
|
a.workspace = root;
|
|
49
|
+
if (a.path == null && DIR_DEFAULTED.has(name))
|
|
50
|
+
a.path = root;
|
|
53
51
|
return a;
|
|
54
52
|
}
|
|
55
53
|
const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this secondary guard never fires first
|
|
56
|
-
import { mutationLanded } from "./mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
|
|
57
|
-
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]); // poll/status tools — repeated calls are legit, never guarded
|
|
58
54
|
// Unique fallback id per Executor instance, so two sessions with no sessionId and no root (the
|
|
59
55
|
// foreground and a read-only sub-agent lane) still get DISTINCT shell keys. One Executor lives for
|
|
60
56
|
// its session's whole lifetime (the Session is constructed once and reused across turns), so this id
|
|
@@ -76,12 +72,27 @@ export class Executor {
|
|
|
76
72
|
this.shellKey = shellKey || `exec-${++_execSeq}`;
|
|
77
73
|
}
|
|
78
74
|
seen = new Map();
|
|
75
|
+
/** A one-turn root (a mentor-wake whose brief names a worktree): wins over `root` until cleared. */
|
|
76
|
+
turnRoot;
|
|
77
|
+
/** Root THIS turn's tool calls under `dir` (undefined clears it). Session sets it at a wake turn's start and clears it in finally. */
|
|
78
|
+
setTurnRoot(dir) {
|
|
79
|
+
this.releaseTurnRoot?.();
|
|
80
|
+
this.releaseTurnRoot = undefined;
|
|
81
|
+
this.turnRoot = dir || undefined;
|
|
82
|
+
if (this.turnRoot)
|
|
83
|
+
this.releaseTurnRoot = allowSandboxWriteRoot(this.turnRoot); // strict mode writes there too
|
|
84
|
+
}
|
|
85
|
+
releaseTurnRoot;
|
|
86
|
+
get effectiveRoot() {
|
|
87
|
+
return this.turnRoot ?? this.root;
|
|
88
|
+
}
|
|
79
89
|
resetTurn() {
|
|
80
90
|
this.seen.clear();
|
|
81
91
|
}
|
|
82
92
|
async execute(name, rawArgs, report) {
|
|
83
|
-
const
|
|
84
|
-
|
|
93
|
+
const root = this.effectiveRoot;
|
|
94
|
+
const args = root ? rootArgs(name, rawArgs, root) : rawArgs;
|
|
95
|
+
if (!POLLERS.has(name) && !IDEMPOTENT.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
|
|
85
96
|
const key = `${name} ${JSON.stringify(args)}`;
|
|
86
97
|
const count = (this.seen.get(key) ?? 0) + 1;
|
|
87
98
|
this.seen.set(key, count);
|
|
@@ -120,7 +131,7 @@ export class Executor {
|
|
|
120
131
|
};
|
|
121
132
|
/** Same resolution the tools apply (root join, ~ expansion), done lexically so a not-yet-written file still keys. */
|
|
122
133
|
resolveKey(p, argName) {
|
|
123
|
-
return KEY_PATH_ARG.test(argName) && !URL_LIKE.test(p) ? resolve(this.
|
|
134
|
+
return KEY_PATH_ARG.test(argName) && !URL_LIKE.test(p) ? resolve(this.effectiveRoot ?? process.cwd(), expandPath(p)) : p;
|
|
124
135
|
}
|
|
125
136
|
async executeParallel(calls, onSettle, signal, onStart) {
|
|
126
137
|
// BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
|
|
@@ -130,8 +141,7 @@ export class Executor {
|
|
|
130
141
|
// Matching Cursor for shells: when this round has ≥2 bash/shell_exec calls, run them as ephemeral
|
|
131
142
|
// one-shots so the persistent ShellSession FIFO cannot serialize wall-clock. A lone bash still
|
|
132
143
|
// uses the persistent session (cwd/env + ctrl+b detach stick). See shellExecMode.
|
|
133
|
-
const
|
|
134
|
-
const shellCount = calls.reduce((n, c) => n + (SHELL_TOOLS.has(c.name) ? 1 : 0), 0);
|
|
144
|
+
const shellCount = calls.reduce((n, c) => n + (SHELL_FOREGROUND.has(c.name) ? 1 : 0), 0);
|
|
135
145
|
const mode = shellCount >= 2 ? "ephemeral" : "persistent";
|
|
136
146
|
return shellExecMode.run(mode, () => runBatch(calls, {
|
|
137
147
|
classify: this.sched.classify,
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// One door for generation: image_generate posts to OUR gateway's `image` route, and
|
|
2
|
+
// the router owns which render servers back it (legs, maxInflight, canary-gated health). A render takes minutes and the
|
|
3
|
+
// public edge cuts a response at ~100 s, so each request is a router job (Prefer: respond-async): submitted once, then
|
|
4
|
+
// polled until the route's answer is ready. Gateways in order: the local router on loopback (no token), then the public
|
|
5
|
+
// gateway with the signed-in Operator token. A router without jobs answers the POST itself, which is taken as is.
|
|
6
|
+
import { getOperatorToken, operatorTrustedUrl } from "../engine/aurora.js";
|
|
7
|
+
import { GATEWAY_BASE, LOCAL_GATEWAY_BASE } from "../router/models.js";
|
|
8
|
+
export const GENERATION_ROUTES = { image: "image" };
|
|
9
|
+
const PATHS = { image: "/images/generations" };
|
|
10
|
+
const SUBMIT_TIMEOUT_MS = 30_000;
|
|
11
|
+
const POLL_MS = 5_000;
|
|
12
|
+
const isLoopback = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(u);
|
|
13
|
+
/** The gateways to ask, in order. A signed-out public gateway stays listed with `skip`, so the "down" line says why. */
|
|
14
|
+
export function generationGateways(o = {}) {
|
|
15
|
+
const local = (o.localBase ?? LOCAL_GATEWAY_BASE).replace(/\/$/, "");
|
|
16
|
+
const pub = (o.publicBase ?? GATEWAY_BASE).replace(/\/$/, "");
|
|
17
|
+
const token = !isLoopback(pub) && operatorTrustedUrl(pub) ? getOperatorToken() || process.env.KODE_OPERATOR_TOKEN : undefined;
|
|
18
|
+
return [
|
|
19
|
+
{ base: local, auth: {}, label: "local gateway" },
|
|
20
|
+
{ base: pub, auth: token ? { Authorization: `Bearer ${token}` } : {}, label: "0perator gateway", ...(token ? {} : { skip: "not signed in" }) },
|
|
21
|
+
];
|
|
22
|
+
}
|
|
23
|
+
/** Why a router said no, in plain words: busy (every leg at capacity, or the queue full or timed out) or not available. Never a host, port or leg name. */
|
|
24
|
+
async function refusal(res) {
|
|
25
|
+
const j = (await res.json().catch(() => null));
|
|
26
|
+
if (j?.error?.tried?.some((t) => /maxInflight|busy|queue/i.test(t.reason ?? "")))
|
|
27
|
+
return "busy";
|
|
28
|
+
return "unavailable";
|
|
29
|
+
}
|
|
30
|
+
async function viaGateway(gw, kind, body, timeoutMs, deadline, pollMs) {
|
|
31
|
+
const headers = { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...gw.auth };
|
|
32
|
+
let res;
|
|
33
|
+
try {
|
|
34
|
+
res = await fetch(`${gw.base}${PATHS[kind]}`, {
|
|
35
|
+
method: "POST", headers: { ...headers, Prefer: "respond-async" }, signal: AbortSignal.timeout(Math.max(1, Math.min(SUBMIT_TIMEOUT_MS, deadline - Date.now()))),
|
|
36
|
+
body: JSON.stringify({ ...body, model: GENERATION_ROUTES[kind] }),
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return { down: "unreachable" };
|
|
41
|
+
}
|
|
42
|
+
if (res.status === 202) {
|
|
43
|
+
const id = (await res.json().catch(() => null))?.id;
|
|
44
|
+
if (typeof id !== "string")
|
|
45
|
+
return { down: "accepted the job without an id", started: true };
|
|
46
|
+
// From here a render is running: a slow or lost answer is reported, never retried on another gateway (a second render).
|
|
47
|
+
for (;;) {
|
|
48
|
+
if (Date.now() + pollMs > deadline)
|
|
49
|
+
return { down: `no answer in ${Math.round(timeoutMs / 1000)}s (job ${id} still running)`, started: true };
|
|
50
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
51
|
+
try {
|
|
52
|
+
res = await fetch(`${gw.base}/jobs/${id}`, { headers, signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS) });
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
continue; // one failed poll is not a failed render
|
|
56
|
+
}
|
|
57
|
+
if (res.status === 202) {
|
|
58
|
+
await res.body?.cancel();
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (res.status === 404)
|
|
62
|
+
return { down: `lost job ${id} (the router restarted or it expired)`, started: true };
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (!res.ok)
|
|
67
|
+
return { down: await refusal(res) };
|
|
68
|
+
const json = (await res.json().catch(() => null));
|
|
69
|
+
if (!json)
|
|
70
|
+
return { down: "returned no JSON", started: true };
|
|
71
|
+
const backend = res.headers.get("x-0perator-backend") ?? undefined;
|
|
72
|
+
return { json, ...(backend ? { backend } : {}) };
|
|
73
|
+
}
|
|
74
|
+
/** One generation through the first gateway that serves it. Throws one plain line when none does. */
|
|
75
|
+
export async function generate(gateways, kind, body, timeoutMs, pollMs = POLL_MS) {
|
|
76
|
+
const deadline = Date.now() + timeoutMs;
|
|
77
|
+
const down = [];
|
|
78
|
+
let started = false;
|
|
79
|
+
for (const gw of gateways) {
|
|
80
|
+
const r = gw.skip ? { down: gw.skip } : await viaGateway(gw, kind, body, timeoutMs, deadline, pollMs);
|
|
81
|
+
if ("json" in r)
|
|
82
|
+
return r;
|
|
83
|
+
down.push(r.down);
|
|
84
|
+
if (r.started) {
|
|
85
|
+
started = true;
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (started)
|
|
90
|
+
throw new Error(`Image generation didn't finish in time (${down[down.length - 1]}). Check again shortly rather than resubmitting.`);
|
|
91
|
+
if (down.includes("busy"))
|
|
92
|
+
throw new Error("Image generation is busy — queued requests are waiting on a render. Try again in a few minutes.");
|
|
93
|
+
throw new Error("Image generation isn't available right now. Not worth retrying this turn.");
|
|
94
|
+
}
|