@0perator/operator 0.0.7 → 0.1.21
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/auth/client.js +17 -0
- package/dist/auth/commands.js +124 -27
- package/dist/background/index.js +59 -18
- package/dist/cli.js +129 -14
- package/dist/config/settings.js +4 -1
- package/dist/engine/agent.js +24 -6
- package/dist/engine/aurora.js +20 -4
- package/dist/engine/grandmaster.js +172 -0
- package/dist/memory/index.js +0 -0
- package/dist/session.js +1 -0
- package/dist/tools/computer.js +279 -0
- package/dist/tools/registry.js +215 -11
- package/dist/tools/sandbox.js +129 -13
- package/dist/ui/App.js +3 -2
- package/dist/ui/ApprovalPrompt.js +45 -0
- package/dist/ui/AuthScreen.js +2 -2
- package/dist/ui/BgPanel.js +12 -1
- package/dist/ui/Composer.js +11 -2
- package/dist/ui/Markdown.js +76 -0
- package/dist/ui/Masthead.js +78 -0
- package/dist/ui/StatusRule.js +12 -3
- package/dist/ui/Transcript.js +8 -3
- package/dist/update.js +16 -4
- package/package.json +2 -1
package/dist/engine/agent.js
CHANGED
|
@@ -147,6 +147,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
147
147
|
tools: opts.toolSchemas,
|
|
148
148
|
signal: opts.signal,
|
|
149
149
|
onDelta: opts.onDelta,
|
|
150
|
+
onReasoning: opts.onReasoning,
|
|
150
151
|
});
|
|
151
152
|
tokensTotal += response.tokens ?? 0;
|
|
152
153
|
genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
|
|
@@ -214,15 +215,32 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
214
215
|
continue;
|
|
215
216
|
}
|
|
216
217
|
const final = stripScratchpad(recovered.cleanedContent);
|
|
217
|
-
// Empty
|
|
218
|
-
//
|
|
219
|
-
//
|
|
218
|
+
// Empty round — two very different causes, handled differently so we never (a) inject a user-role
|
|
219
|
+
// directive that renders as the user speaking and gets answered as the request, nor (b) treat a
|
|
220
|
+
// budget-truncated turn as a "dud".
|
|
220
221
|
if (!final && emptyRetries < MAX_EMPTY_RETRIES) {
|
|
221
222
|
emptyRetries += 1;
|
|
222
|
-
|
|
223
|
-
|
|
223
|
+
if (response.stopReason === "length") {
|
|
224
|
+
// Thinking spent the whole output budget before any content (finish_reason "length"). This is
|
|
225
|
+
// TRUNCATION, not a dud. Free output room by compacting, then retry the SAME request. If nothing
|
|
226
|
+
// can be shed, fall through to finalize with the reasoning we did capture.
|
|
227
|
+
const before = conversation.all.length;
|
|
228
|
+
conversation.replaceAll(await compact(conversation.all, compactionOptsFor(endpoint)));
|
|
229
|
+
if (conversation.all.length < before)
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
// Genuine empty (finish "stop"): after tool calls the tool RESULTS are already in the conversation,
|
|
234
|
+
// so just retry — the model gets another shot to write the final answer WITH that output in context.
|
|
235
|
+
// We inject NOTHING: a 2nd system message 400s the endpoint (SPEC §1, one system message only), and
|
|
236
|
+
// a user-role nudge would render as the user speaking and be answered as the request (the leak).
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
224
239
|
}
|
|
225
|
-
const answer = final || stripScratchpad(response.reasoningContent ?? "") ||
|
|
240
|
+
const answer = final || stripScratchpad(response.reasoningContent ?? "") ||
|
|
241
|
+
(response.stopReason === "length"
|
|
242
|
+
? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
|
|
243
|
+
: "(the model returned an empty response — try rephrasing.)");
|
|
226
244
|
conversation.assistant(answer);
|
|
227
245
|
return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal };
|
|
228
246
|
}
|
package/dist/engine/aurora.js
CHANGED
|
@@ -108,9 +108,16 @@ async function* streamDeltas(messages, o) {
|
|
|
108
108
|
// llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
|
|
109
109
|
if (j.timings || j.usage)
|
|
110
110
|
o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms });
|
|
111
|
-
const
|
|
112
|
-
|
|
111
|
+
const choice = j.choices?.[0];
|
|
112
|
+
// finish_reason is a sibling of delta (often on a final chunk whose delta is {} or absent).
|
|
113
|
+
// Attach it to the yielded delta, and still yield a bare {finish_reason} when there's no delta,
|
|
114
|
+
// so the consumer always sees WHY generation ended.
|
|
115
|
+
const delta = choice?.delta ?? (choice?.finish_reason ? {} : undefined);
|
|
116
|
+
if (delta) {
|
|
117
|
+
if (choice?.finish_reason)
|
|
118
|
+
delta.finish_reason = choice.finish_reason;
|
|
113
119
|
yield delta;
|
|
120
|
+
}
|
|
114
121
|
}
|
|
115
122
|
catch { }
|
|
116
123
|
}
|
|
@@ -147,6 +154,7 @@ export async function chat(messages, o) {
|
|
|
147
154
|
let reasoning = "";
|
|
148
155
|
let degenerate = false;
|
|
149
156
|
let sinceCheck = 0;
|
|
157
|
+
let finishReason; // API choices[0].finish_reason — WHY generation ended
|
|
150
158
|
const acc = new Map();
|
|
151
159
|
const meta = {};
|
|
152
160
|
const oo = { ...o, onMeta: (m) => { if (m.tokens != null)
|
|
@@ -157,8 +165,12 @@ export async function chat(messages, o) {
|
|
|
157
165
|
content += delta.content;
|
|
158
166
|
o.onDelta?.(delta.content);
|
|
159
167
|
}
|
|
160
|
-
if (delta.reasoning_content)
|
|
168
|
+
if (delta.reasoning_content) {
|
|
161
169
|
reasoning += delta.reasoning_content;
|
|
170
|
+
o.onReasoning?.(delta.reasoning_content);
|
|
171
|
+
}
|
|
172
|
+
if (delta.finish_reason)
|
|
173
|
+
finishReason = delta.finish_reason;
|
|
162
174
|
if (delta.tool_calls) {
|
|
163
175
|
for (const tc of delta.tool_calls) {
|
|
164
176
|
const idx = tc.index ?? 0;
|
|
@@ -196,7 +208,11 @@ export async function chat(messages, o) {
|
|
|
196
208
|
type: "function",
|
|
197
209
|
function: { name: e.name, arguments: e.args },
|
|
198
210
|
}));
|
|
199
|
-
|
|
211
|
+
// Degeneracy (our loop breaker) wins; else map the API finish_reason. A tool-calling turn ending on
|
|
212
|
+
// "length" isn't a truncated ANSWER, so only flag length/content_filter when NO tool calls were made.
|
|
213
|
+
const apiStop = finishReason === "length" ? "length" : finishReason === "content_filter" ? "content_filter" : undefined;
|
|
214
|
+
const stopReason = degenerate ? "repetition" : (acc.size === 0 ? apiStop : undefined);
|
|
215
|
+
return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens: meta.tokens, genMs: meta.genMs };
|
|
200
216
|
}
|
|
201
217
|
/** GET {base}/health → true iff {"status":"ok"}. Used by Router (SPEC §4) for self-heal failover. */
|
|
202
218
|
export async function health(base) {
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Grandmaster sub-agent orchestration (SPEC/grandmaster-subagents.md) — four Aurora-tuned mechanisms
|
|
2
|
+
// that make sub-agent spawns reliable and fast, living in the shared engine so every surface inherits
|
|
3
|
+
// them:
|
|
4
|
+
// 1. Structured briefs — a self-contained brief the child can act on without the parent conversation.
|
|
5
|
+
// 2. Schema-enforced final_answer + ONE repair round — validate the child's JSON; on failure feed the
|
|
6
|
+
// error back once and re-run just the final step. The biggest Aurora-specific win.
|
|
7
|
+
// 3. Verify-before-"done" — a result isn't complete until a task-type verify passes (here: the claimed
|
|
8
|
+
// files actually exist — read-after-write; a declared verify_command is surfaced for the child to run).
|
|
9
|
+
// 4. Size-routed spawn — a heuristic picks the lane (reasoning = full 1M | fast = small/bounded) so
|
|
10
|
+
// mechanical children don't pin the single 1M slot.
|
|
11
|
+
// Pure + framework-agnostic; node builtins (fs for verify) load lazily so the neutral bundle is unaffected.
|
|
12
|
+
const nodeImport = (m) => import(m);
|
|
13
|
+
// Infer the task type from a free-form objective when the caller didn't declare one — keeps the tool
|
|
14
|
+
// usable with just a task string while still selecting the right schema + verify + lane.
|
|
15
|
+
export function inferType(objective) {
|
|
16
|
+
const s = objective.toLowerCase();
|
|
17
|
+
if (/\b(plan|design|architect|strategy|approach|outline)\b/.test(s))
|
|
18
|
+
return "plan";
|
|
19
|
+
if (/\b(review|audit|critique|assess|check .* for)\b/.test(s))
|
|
20
|
+
return "review";
|
|
21
|
+
if (/\b(search|find|look up|research|locate|grep|where is)\b/.test(s))
|
|
22
|
+
return "search";
|
|
23
|
+
if (/\b(edit|fix|implement|add|refactor|write|create|change|rename|update|build)\b/.test(s))
|
|
24
|
+
return "code-edit";
|
|
25
|
+
return "generic";
|
|
26
|
+
}
|
|
27
|
+
// The per-task-type final_answer schema, rendered as a compact JSON example the child fills in.
|
|
28
|
+
export function schemaHintFor(type) {
|
|
29
|
+
switch (type) {
|
|
30
|
+
case "code-edit": return `{ "summary": "<what changed, 1-2 lines>", "files_changed": ["path", ...], "verify_command": "<cmd that proves it, e.g. npm test>", "verified": true|false }`;
|
|
31
|
+
case "search": return `{ "summary": "<what you found>", "results": [{ "path": "...", "detail": "..." }] }`;
|
|
32
|
+
case "review": return `{ "summary": "<overall>", "findings": [{ "severity": "high|med|low", "where": "path:line", "issue": "...", "fix": "..." }] }`;
|
|
33
|
+
case "plan": return `{ "summary": "<the plan in one line>", "steps": ["step 1", "step 2", ...], "risks": ["..."] }`;
|
|
34
|
+
default: return `{ "summary": "<result>", "detail": "<any specifics>" }`;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const REQUIRED = {
|
|
38
|
+
"code-edit": ["summary", "files_changed"],
|
|
39
|
+
search: ["summary", "results"],
|
|
40
|
+
review: ["summary", "findings"],
|
|
41
|
+
plan: ["summary", "steps"],
|
|
42
|
+
generic: ["summary"],
|
|
43
|
+
};
|
|
44
|
+
/** Build the self-contained brief prompt sent to the child (mechanism 1). */
|
|
45
|
+
export function buildBrief(input, cwd) {
|
|
46
|
+
const type = input.type ?? inferType(input.objective);
|
|
47
|
+
return [
|
|
48
|
+
"# Sub-agent brief",
|
|
49
|
+
"You are a focused sub-agent. You CANNOT see the parent conversation — everything you need is here.",
|
|
50
|
+
"",
|
|
51
|
+
"## Objective",
|
|
52
|
+
input.objective.trim(),
|
|
53
|
+
"",
|
|
54
|
+
"## Context",
|
|
55
|
+
input.context?.trim() || `Working directory: ${cwd}. Inspect the repo with your tools; do not assume anything not stated or verifiable.`,
|
|
56
|
+
"",
|
|
57
|
+
"## Deliverable",
|
|
58
|
+
input.deliverable?.trim() || "Achieve the objective, then report concisely what you did and where.",
|
|
59
|
+
"",
|
|
60
|
+
"## Definition of done",
|
|
61
|
+
input.done?.trim() || "The objective is achieved AND verified — the changed files exist and your verify_command (tests/build/grep) passes. Do not claim done on the strength of your own say-so; run the check.",
|
|
62
|
+
"",
|
|
63
|
+
"## Final answer (required)",
|
|
64
|
+
"When finished, your LAST output must be ONLY a fenced ```json block matching this schema — no prose after it:",
|
|
65
|
+
"```json",
|
|
66
|
+
schemaHintFor(type),
|
|
67
|
+
"```",
|
|
68
|
+
"Use null for any field you genuinely cannot fill.",
|
|
69
|
+
].join("\n");
|
|
70
|
+
}
|
|
71
|
+
// Pull the last JSON object out of the child's output — prefer a fenced ```json block, else the last
|
|
72
|
+
// balanced {...}. Reasoners often wrap the answer or trail whitespace; take the LAST candidate.
|
|
73
|
+
function lastJsonBlock(text) {
|
|
74
|
+
const fences = [...text.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
|
|
75
|
+
for (let i = fences.length - 1; i >= 0; i--) {
|
|
76
|
+
const body = fences[i][1].trim();
|
|
77
|
+
if (body.startsWith("{"))
|
|
78
|
+
return body;
|
|
79
|
+
}
|
|
80
|
+
// Fallback: last top-level {...} by scanning for a balanced object from the last "{".
|
|
81
|
+
const start = text.lastIndexOf("{");
|
|
82
|
+
if (start === -1)
|
|
83
|
+
return null;
|
|
84
|
+
let depth = 0;
|
|
85
|
+
for (let i = start; i < text.length; i++) {
|
|
86
|
+
if (text[i] === "{")
|
|
87
|
+
depth++;
|
|
88
|
+
else if (text[i] === "}") {
|
|
89
|
+
depth--;
|
|
90
|
+
if (depth === 0)
|
|
91
|
+
return text.slice(start, i + 1);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
/** Extract + validate the child's final_answer against its task-type schema (mechanism 2). */
|
|
97
|
+
export function extractFinalAnswer(text, type) {
|
|
98
|
+
const block = lastJsonBlock(text);
|
|
99
|
+
if (!block)
|
|
100
|
+
return { ok: false, errors: ["no JSON final_answer block found"], raw: text };
|
|
101
|
+
let v;
|
|
102
|
+
try {
|
|
103
|
+
v = JSON.parse(block);
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
return { ok: false, errors: [`final_answer is not valid JSON: ${e instanceof Error ? e.message : String(e)}`], raw: text };
|
|
107
|
+
}
|
|
108
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
109
|
+
return { ok: false, errors: ["final_answer must be a JSON object"], raw: text };
|
|
110
|
+
const obj = v;
|
|
111
|
+
const missing = REQUIRED[type].filter((k) => !(k in obj) || obj[k] == null);
|
|
112
|
+
if (missing.length)
|
|
113
|
+
return { ok: false, value: obj, errors: [`missing required field(s): ${missing.join(", ")}`], raw: text };
|
|
114
|
+
return { ok: true, value: obj, raw: text };
|
|
115
|
+
}
|
|
116
|
+
/** The one-shot repair prompt fed back to the child on a schema failure (mechanism 2). */
|
|
117
|
+
export function repairPrompt(errors, type) {
|
|
118
|
+
return [
|
|
119
|
+
`Your final_answer failed validation: ${errors.join("; ")}.`,
|
|
120
|
+
"Re-emit ONLY a valid ```json block matching this schema exactly — no prose, no other text:",
|
|
121
|
+
"```json",
|
|
122
|
+
schemaHintFor(type),
|
|
123
|
+
"```",
|
|
124
|
+
].join("\n");
|
|
125
|
+
}
|
|
126
|
+
/** Verify the child's claim WITHOUT trusting its say-so (mechanism 3). Orchestrator-side, cheap + real:
|
|
127
|
+
* a code-edit's claimed files_changed must actually exist on disk (read-after-write). A declared
|
|
128
|
+
* verify_command is surfaced (the child was told to run it) but not re-run here (no exec plumbing in the
|
|
129
|
+
* orchestrator yet — that's the documented next step). Non-code tasks pass structurally. */
|
|
130
|
+
export async function verifyFinalAnswer(value, type, cwd) {
|
|
131
|
+
if (type !== "code-edit")
|
|
132
|
+
return { verified: true, detail: "no file-level verify for this task type" };
|
|
133
|
+
const files = Array.isArray(value.files_changed) ? value.files_changed.map(String) : [];
|
|
134
|
+
if (files.length === 0)
|
|
135
|
+
return { verified: false, detail: "code-edit reported no files_changed" };
|
|
136
|
+
try {
|
|
137
|
+
const { stat } = await nodeImport("node:fs/promises");
|
|
138
|
+
const { isAbsolute, join } = await nodeImport("node:path");
|
|
139
|
+
const missing = [];
|
|
140
|
+
for (const f of files) {
|
|
141
|
+
const p = isAbsolute(f) ? f : join(cwd, f);
|
|
142
|
+
try {
|
|
143
|
+
await stat(p);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
missing.push(f);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (missing.length)
|
|
150
|
+
return { verified: false, detail: `claimed files do not exist: ${missing.join(", ")}` };
|
|
151
|
+
const vc = typeof value.verify_command === "string" ? value.verify_command : "";
|
|
152
|
+
return { verified: true, detail: `${files.length} file(s) exist${vc ? ` — child was told to run: ${vc}` : ""}` };
|
|
153
|
+
}
|
|
154
|
+
catch (e) {
|
|
155
|
+
return { verified: false, detail: `verify error: ${e instanceof Error ? e.message : String(e)}` };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// --- 4. size-routed spawn -----------------------------------------------------------
|
|
159
|
+
/** Pick the lane by task size/complexity (mechanism 4). reasoning = full 1M; fast = small/bounded model
|
|
160
|
+
* for mechanical children. A caller `heavy` hint forces reasoning; plan/review are always reasoning. */
|
|
161
|
+
export function routeLane(brief, hint) {
|
|
162
|
+
if (hint?.heavy)
|
|
163
|
+
return "reasoning";
|
|
164
|
+
const type = hint?.type;
|
|
165
|
+
if (type === "plan" || type === "review")
|
|
166
|
+
return "reasoning";
|
|
167
|
+
const long = brief.length > 1200;
|
|
168
|
+
const mechanical = /\b(rename|grep|format|lint|list|count|read|locate|find)\b/i.test(brief);
|
|
169
|
+
if (type === "search" || (mechanical && !long))
|
|
170
|
+
return "fast";
|
|
171
|
+
return long ? "reasoning" : "fast";
|
|
172
|
+
}
|
package/dist/memory/index.js
CHANGED
|
Binary file
|
package/dist/session.js
CHANGED
|
@@ -241,6 +241,7 @@ export class Session {
|
|
|
241
241
|
temperature: this.temperature,
|
|
242
242
|
signal: controller.signal,
|
|
243
243
|
onDelta: h.onDelta,
|
|
244
|
+
onReasoning: h.onReasoning,
|
|
244
245
|
onRoute: (ep) => h.onRoute?.(ep.label ?? "aurora", this.ctxPct()),
|
|
245
246
|
onToolStart: h.onToolStart,
|
|
246
247
|
onToolBatch: h.onToolBatch,
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
const nodeImport = (m) => import(m);
|
|
2
|
+
// Module-level enable flag: flipped once at startup from settings/env. Tools read it on every call so a
|
|
3
|
+
// registry entry that somehow outlives a disable can never act.
|
|
4
|
+
let ENABLED = false;
|
|
5
|
+
export function setComputerEnabled(on) { ENABLED = on; }
|
|
6
|
+
export function computerEnabled() { return ENABLED; }
|
|
7
|
+
let _pexec = null;
|
|
8
|
+
async function pexecFile(file, args, opts) {
|
|
9
|
+
if (!_pexec) {
|
|
10
|
+
const { execFile } = await nodeImport("node:child_process");
|
|
11
|
+
const { promisify } = await nodeImport("node:util");
|
|
12
|
+
_pexec = promisify(execFile);
|
|
13
|
+
}
|
|
14
|
+
return _pexec(file, args, opts);
|
|
15
|
+
}
|
|
16
|
+
function str(v, fallback = "") {
|
|
17
|
+
return v === undefined || v === null ? fallback : String(v);
|
|
18
|
+
}
|
|
19
|
+
const DISABLED_MSG = "computer control is disabled. Enable it with KODE_COMPUTER=1 (or computer.enabled in settings.json), " +
|
|
20
|
+
"and grant the terminal app macOS permissions (run computer_doctor for the exact steps).";
|
|
21
|
+
// macOS is the only supported host for now (osascript/screencapture). Fail clearly elsewhere rather
|
|
22
|
+
// than silently no-op.
|
|
23
|
+
function macOnly() {
|
|
24
|
+
return process.platform === "darwin" ? null : "computer control currently supports macOS only (this host is " + process.platform + ").";
|
|
25
|
+
}
|
|
26
|
+
// Run one AppleScript via osascript. Returns stdout, or a clear error. A permission-denied from TCC
|
|
27
|
+
// surfaces here as osascript's own "Not authorized to send Apple events" / "-1743" — we translate it.
|
|
28
|
+
async function osa(script, timeout = 30_000) {
|
|
29
|
+
try {
|
|
30
|
+
const { stdout, stderr } = await pexecFile("osascript", ["-e", script], { timeout });
|
|
31
|
+
const out = (String(stdout) + (stderr ? `\n[stderr] ${stderr}` : "")).trim();
|
|
32
|
+
return out || "(ok)";
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
const msg = String(e?.stderr ?? e?.message ?? e);
|
|
36
|
+
if (/-1743|not authoriz|assistive|accessibility|Apple events/i.test(msg)) {
|
|
37
|
+
return `error: macOS blocked this (TCC). ${msg.trim()}\nGrant the hosting terminal app the needed permission in System Settings → Privacy & Security, then retry. Run computer_doctor for specifics.`;
|
|
38
|
+
}
|
|
39
|
+
return `error: osascript failed: ${msg.trim()}`;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// AppleScript string literal escape: backslash and double-quote.
|
|
43
|
+
function q(s) { return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); }
|
|
44
|
+
async function appOpen(args) {
|
|
45
|
+
if (!ENABLED)
|
|
46
|
+
return DISABLED_MSG;
|
|
47
|
+
const mac = macOnly();
|
|
48
|
+
if (mac)
|
|
49
|
+
return mac;
|
|
50
|
+
const app = str(args.app);
|
|
51
|
+
if (!app)
|
|
52
|
+
return "error: no app given (e.g. { app: \"Safari\" })";
|
|
53
|
+
// `open -a` launches or brings-to-front; then activate for focus. `open` needs no special TCC grant.
|
|
54
|
+
try {
|
|
55
|
+
await pexecFile("open", ["-a", app], { timeout: 15_000 });
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
return `error: couldn't open "${app}": ${String(e?.stderr ?? e?.message ?? e).trim()}`;
|
|
59
|
+
}
|
|
60
|
+
return `opened ${app}`;
|
|
61
|
+
}
|
|
62
|
+
async function appActivate(args) {
|
|
63
|
+
if (!ENABLED)
|
|
64
|
+
return DISABLED_MSG;
|
|
65
|
+
const mac = macOnly();
|
|
66
|
+
if (mac)
|
|
67
|
+
return mac;
|
|
68
|
+
const app = str(args.app);
|
|
69
|
+
if (!app)
|
|
70
|
+
return "error: no app given";
|
|
71
|
+
return osa(`tell application "${q(app)}" to activate`);
|
|
72
|
+
}
|
|
73
|
+
async function runAppleScript(args) {
|
|
74
|
+
if (!ENABLED)
|
|
75
|
+
return DISABLED_MSG;
|
|
76
|
+
const mac = macOnly();
|
|
77
|
+
if (mac)
|
|
78
|
+
return mac;
|
|
79
|
+
const script = str(args.script);
|
|
80
|
+
if (!script)
|
|
81
|
+
return "error: no script given";
|
|
82
|
+
return osa(script, Number(args.timeout_ms ?? 30_000));
|
|
83
|
+
}
|
|
84
|
+
async function typeText(args) {
|
|
85
|
+
if (!ENABLED)
|
|
86
|
+
return DISABLED_MSG;
|
|
87
|
+
const mac = macOnly();
|
|
88
|
+
if (mac)
|
|
89
|
+
return mac;
|
|
90
|
+
const text = str(args.text);
|
|
91
|
+
if (!text)
|
|
92
|
+
return "error: no text given";
|
|
93
|
+
// System Events keystroke needs Accessibility. Optionally focus an app first.
|
|
94
|
+
const app = str(args.app);
|
|
95
|
+
const focus = app ? `tell application "${q(app)}" to activate\ndelay 0.15\n` : "";
|
|
96
|
+
return osa(`${focus}tell application "System Events" to keystroke "${q(text)}"`);
|
|
97
|
+
}
|
|
98
|
+
// Named keys + modifier combos via System Events. `key` is a friendly name (return, tab, escape, space,
|
|
99
|
+
// delete, arrows, or a single character); `modifiers` is any of command/control/option/shift.
|
|
100
|
+
const KEY_CODES = {
|
|
101
|
+
return: 36, enter: 36, tab: 48, space: 49, delete: 51, backspace: 51, escape: 27, esc: 27,
|
|
102
|
+
left: 123, right: 124, down: 125, up: 126, home: 115, end: 119, pageup: 116, pagedown: 121,
|
|
103
|
+
f1: 122, f2: 120, f3: 99, f4: 118, f5: 96, f6: 97, f7: 98, f8: 100, f9: 101, f10: 109, f11: 103, f12: 111,
|
|
104
|
+
};
|
|
105
|
+
async function pressKey(args) {
|
|
106
|
+
if (!ENABLED)
|
|
107
|
+
return DISABLED_MSG;
|
|
108
|
+
const mac = macOnly();
|
|
109
|
+
if (mac)
|
|
110
|
+
return mac;
|
|
111
|
+
const key = str(args.key).toLowerCase().trim();
|
|
112
|
+
if (!key)
|
|
113
|
+
return "error: no key given (e.g. { key: \"return\" } or { key: \"a\", modifiers: [\"command\"] })";
|
|
114
|
+
const mods = Array.isArray(args.modifiers) ? args.modifiers.map((m) => String(m).toLowerCase()) : [];
|
|
115
|
+
const modMap = { command: "command down", cmd: "command down", control: "control down", ctrl: "control down", option: "option down", alt: "option down", shift: "shift down" };
|
|
116
|
+
const using = mods.map((m) => modMap[m]).filter(Boolean);
|
|
117
|
+
const usingClause = using.length ? ` using {${using.join(", ")}}` : "";
|
|
118
|
+
const app = str(args.app);
|
|
119
|
+
const focus = app ? `tell application "${q(app)}" to activate\ndelay 0.15\n` : "";
|
|
120
|
+
if (key in KEY_CODES) {
|
|
121
|
+
return osa(`${focus}tell application "System Events" to key code ${KEY_CODES[key]}${usingClause}`);
|
|
122
|
+
}
|
|
123
|
+
if (key.length === 1) {
|
|
124
|
+
return osa(`${focus}tell application "System Events" to keystroke "${q(key)}"${usingClause}`);
|
|
125
|
+
}
|
|
126
|
+
return `error: unknown key "${key}". Use a single character or one of: ${Object.keys(KEY_CODES).join(", ")}.`;
|
|
127
|
+
}
|
|
128
|
+
// Mouse click at absolute screen coordinates. Uses cliclick when present (accurate, honors real cursor);
|
|
129
|
+
// otherwise falls back to a System Events "click at" (needs Accessibility, less reliable) and says so.
|
|
130
|
+
async function click(args) {
|
|
131
|
+
if (!ENABLED)
|
|
132
|
+
return DISABLED_MSG;
|
|
133
|
+
const mac = macOnly();
|
|
134
|
+
if (mac)
|
|
135
|
+
return mac;
|
|
136
|
+
const x = Number(args.x), y = Number(args.y);
|
|
137
|
+
if (!Number.isFinite(x) || !Number.isFinite(y))
|
|
138
|
+
return "error: need numeric x and y (screen coordinates)";
|
|
139
|
+
// Prefer cliclick (brew install cliclick) — a proper synthetic click.
|
|
140
|
+
try {
|
|
141
|
+
await pexecFile("cliclick", [`c:${Math.round(x)},${Math.round(y)}`], { timeout: 10_000 });
|
|
142
|
+
return `clicked at ${Math.round(x)},${Math.round(y)}`;
|
|
143
|
+
}
|
|
144
|
+
catch (e) {
|
|
145
|
+
if (/ENOENT/.test(String(e?.code ?? e?.message ?? ""))) {
|
|
146
|
+
const r = await osa(`tell application "System Events" to click at {${Math.round(x)}, ${Math.round(y)}}`);
|
|
147
|
+
return r.startsWith("error") ? r : `clicked at ${Math.round(x)},${Math.round(y)} (via System Events; install cliclick — \`brew install cliclick\` — for reliable clicks)`;
|
|
148
|
+
}
|
|
149
|
+
return `error: click failed: ${String(e?.stderr ?? e?.message ?? e).trim()}`;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Capture the screen to a PNG file and return the path. NOTE: image INPUT to Aurora is not wired yet
|
|
153
|
+
// (GAP #57), so the model cannot yet "see" this capture — the file is saved for the user / future
|
|
154
|
+
// vision input. Needs Screen Recording permission or the capture is a black frame.
|
|
155
|
+
async function screenshot(args) {
|
|
156
|
+
if (!ENABLED)
|
|
157
|
+
return DISABLED_MSG;
|
|
158
|
+
const mac = macOnly();
|
|
159
|
+
if (mac)
|
|
160
|
+
return mac;
|
|
161
|
+
const { tmpdir } = await nodeImport("node:os");
|
|
162
|
+
const { join } = await nodeImport("node:path");
|
|
163
|
+
const out = str(args.path) || join(tmpdir(), `operator-shot-${Date.now()}.png`);
|
|
164
|
+
try {
|
|
165
|
+
await pexecFile("screencapture", ["-x", out], { timeout: 15_000 }); // -x = no shutter sound
|
|
166
|
+
const { stat } = await nodeImport("node:fs/promises");
|
|
167
|
+
const s = await stat(out);
|
|
168
|
+
return `saved screenshot → ${out} (${Math.round(s.size / 1024)} KB). Note: Operator can't yet read images back into the model (vision input pending), so use this file directly for now. If it's blank/black, grant Screen Recording to this terminal app.`;
|
|
169
|
+
}
|
|
170
|
+
catch (e) {
|
|
171
|
+
return `error: screencapture failed: ${String(e?.stderr ?? e?.message ?? e).trim()} (grant Screen Recording in System Settings → Privacy & Security)`;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// Probe each capability + binary and report what's wired vs what the owner still needs to grant. Safe:
|
|
175
|
+
// it only reads state (a tiny osascript, checks for binaries), takes no destructive action.
|
|
176
|
+
async function doctor(_args) {
|
|
177
|
+
if (!ENABLED)
|
|
178
|
+
return DISABLED_MSG;
|
|
179
|
+
const mac = macOnly();
|
|
180
|
+
if (mac)
|
|
181
|
+
return mac;
|
|
182
|
+
const lines = ["Operator computer-control preflight (macOS):", ""];
|
|
183
|
+
// osascript present?
|
|
184
|
+
let osaOk = false;
|
|
185
|
+
try {
|
|
186
|
+
await pexecFile("osascript", ["-e", "return 1"], { timeout: 8_000 });
|
|
187
|
+
osaOk = true;
|
|
188
|
+
}
|
|
189
|
+
catch { /* */ }
|
|
190
|
+
lines.push(`${osaOk ? "✓" : "✗"} osascript available (AppleScript / app control)`);
|
|
191
|
+
// Accessibility: System Events keystroke is the canonical probe (harmless: types nothing to a target).
|
|
192
|
+
let axOk = false, axMsg = "";
|
|
193
|
+
try {
|
|
194
|
+
const r = await osa(`tell application "System Events" to return (name of first process whose frontmost is true)`);
|
|
195
|
+
axOk = !r.startsWith("error");
|
|
196
|
+
axMsg = axOk ? `frontmost app: ${r}` : r.split("\n")[0];
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
axMsg = String(e?.message ?? e);
|
|
200
|
+
}
|
|
201
|
+
lines.push(`${axOk ? "✓" : "✗"} Accessibility (keystrokes/clicks) — ${axOk ? axMsg : "NOT granted. System Settings → Privacy & Security → Accessibility → add your terminal app (Terminal/iTerm) and enable it."}`);
|
|
202
|
+
// Screen Recording: capture a 1px region; a granted grab succeeds, ungranted may still write but be black.
|
|
203
|
+
let capOk = false;
|
|
204
|
+
try {
|
|
205
|
+
const { tmpdir } = await nodeImport("node:os");
|
|
206
|
+
const { join } = await nodeImport("node:path");
|
|
207
|
+
const p = join(tmpdir(), `operator-doctor-${Date.now()}.png`);
|
|
208
|
+
await pexecFile("screencapture", ["-x", "-R", "0,0,4,4", p], { timeout: 8_000 });
|
|
209
|
+
const { stat, rm } = await nodeImport("node:fs/promises");
|
|
210
|
+
capOk = (await stat(p)).size > 0;
|
|
211
|
+
await rm(p, { force: true });
|
|
212
|
+
}
|
|
213
|
+
catch { /* */ }
|
|
214
|
+
lines.push(`${capOk ? "✓" : "✗"} screencapture available — ${capOk ? "OK (grant Screen Recording if captures come out black: System Settings → Privacy & Security → Screen Recording)" : "failed"}`);
|
|
215
|
+
// cliclick (optional, for reliable clicks)
|
|
216
|
+
let cliOk = false;
|
|
217
|
+
try {
|
|
218
|
+
await pexecFile("cliclick", ["-V"], { timeout: 6_000 });
|
|
219
|
+
cliOk = true;
|
|
220
|
+
}
|
|
221
|
+
catch { /* */ }
|
|
222
|
+
lines.push(`${cliOk ? "✓" : "○"} cliclick ${cliOk ? "installed (reliable mouse clicks)" : "not installed (optional — `brew install cliclick` for accurate clicks; without it, clicks fall back to System Events)"}`);
|
|
223
|
+
lines.push("", "Automation (controlling other apps) auto-prompts the first time Operator talks to each app — approve it when macOS asks.");
|
|
224
|
+
lines.push("Full Disk Access is only needed to read protected folders (Mail, Messages, other apps' data): System Settings → Privacy & Security → Full Disk Access.");
|
|
225
|
+
return lines.join("\n");
|
|
226
|
+
}
|
|
227
|
+
// The tool set. Names are namespaced `computer_*` / `app_*` so the permission layer can target them as a
|
|
228
|
+
// group. None are `safe` (all mutating/sensitive) — the policy forces them to "ask".
|
|
229
|
+
export const COMPUTER_TOOLS = [
|
|
230
|
+
{
|
|
231
|
+
name: "app_open",
|
|
232
|
+
description: "Open or bring a macOS application to the front by name (e.g. Safari, Notes, Finder). Launches it if not running.",
|
|
233
|
+
parameters: { type: "object", properties: { app: { type: "string", description: "Application name, e.g. \"Safari\"" } }, required: ["app"] },
|
|
234
|
+
run: appOpen,
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
name: "app_activate",
|
|
238
|
+
description: "Focus/activate an already-running macOS app so keystrokes go to it.",
|
|
239
|
+
parameters: { type: "object", properties: { app: { type: "string" } }, required: ["app"] },
|
|
240
|
+
run: appActivate,
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
name: "computer_applescript",
|
|
244
|
+
description: "Run an arbitrary AppleScript via osascript — the general escape hatch for controlling any scriptable macOS app (open a URL in Safari, compose Mail, read Notes, control Music, etc.). Returns the script's result.",
|
|
245
|
+
parameters: { type: "object", properties: { script: { type: "string", description: "AppleScript source" }, timeout_ms: { type: "number" } }, required: ["script"] },
|
|
246
|
+
run: runAppleScript,
|
|
247
|
+
},
|
|
248
|
+
{
|
|
249
|
+
name: "computer_type",
|
|
250
|
+
description: "Type text into the frontmost app (or a named app) as if typed on the keyboard. Requires macOS Accessibility permission.",
|
|
251
|
+
parameters: { type: "object", properties: { text: { type: "string" }, app: { type: "string", description: "optional: activate this app first" } }, required: ["text"] },
|
|
252
|
+
run: typeText,
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
name: "computer_key",
|
|
256
|
+
description: "Press a key or key-combo (e.g. { key: \"return\" }, { key: \"s\", modifiers: [\"command\"] }, { key: \"tab\" }). Requires Accessibility.",
|
|
257
|
+
parameters: { type: "object", properties: { key: { type: "string", description: "return|tab|space|escape|delete|up|down|left|right|home|end|f1..f12, or a single character" }, modifiers: { type: "array", items: { type: "string", enum: ["command", "control", "option", "shift"] } }, app: { type: "string" } }, required: ["key"] },
|
|
258
|
+
run: pressKey,
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
name: "computer_click",
|
|
262
|
+
description: "Click the mouse at absolute screen coordinates (x, y). Uses cliclick if installed, else System Events. Requires Accessibility.",
|
|
263
|
+
parameters: { type: "object", properties: { x: { type: "number" }, y: { type: "number" } }, required: ["x", "y"] },
|
|
264
|
+
run: click,
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
name: "computer_screenshot",
|
|
268
|
+
description: "Capture the screen to a PNG file and return its path. Requires Screen Recording permission. (Note: the model cannot read the image back yet — vision input is pending.)",
|
|
269
|
+
parameters: { type: "object", properties: { path: { type: "string", description: "optional output path; defaults to a temp file" } } },
|
|
270
|
+
run: screenshot,
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
name: "computer_doctor",
|
|
274
|
+
description: "Preflight check: report which macOS permissions (Accessibility, Screen Recording, Automation) and helper binaries are wired for computer control, and exactly what to grant.",
|
|
275
|
+
parameters: { type: "object", properties: {} },
|
|
276
|
+
run: doctor,
|
|
277
|
+
},
|
|
278
|
+
];
|
|
279
|
+
export const COMPUTER_TOOL_NAMES = COMPUTER_TOOLS.map((t) => t.name);
|