@cloxco/clox 0.1.0 → 0.1.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.
Files changed (2) hide show
  1. package/clox.cjs +784 -259
  2. package/package.json +1 -1
package/clox.cjs CHANGED
@@ -3787,19 +3787,50 @@ var init_wrapper = __esm({
3787
3787
  // src/chat.ts
3788
3788
  var chat_exports = {};
3789
3789
  __export(chat_exports, {
3790
- converse: () => converse,
3790
+ StoppedError: () => StoppedError,
3791
3791
  say: () => say,
3792
- sendMessage: () => sendMessage
3792
+ sendMessage: () => sendMessage,
3793
+ startTurn: () => startTurn,
3794
+ stepLabel: () => stepLabel
3793
3795
  });
3794
- var import_crypto2, import_readline, errorText, sendMessage, say, converse;
3796
+ var import_crypto2, stepLabel, stepDetail, errorText, startTurn, StoppedError, sendMessage, say;
3795
3797
  var init_chat = __esm({
3796
3798
  "src/chat.ts"() {
3797
3799
  "use strict";
3798
3800
  import_crypto2 = require("crypto");
3799
- import_readline = __toESM(require("readline"));
3800
3801
  init_wrapper();
3801
3802
  init_api();
3802
3803
  init_logo();
3804
+ stepLabel = (name5) => {
3805
+ const n = name5.toLowerCase();
3806
+ if (n.includes("deepresearch")) return "Running deep research";
3807
+ if (n.includes("xai") || n.includes("news")) return "Searching the news";
3808
+ if (n.includes("image")) return "Finding pictures";
3809
+ if (n.includes("video")) return "Finding videos";
3810
+ if (n.includes("composiosearch") || n.includes("connection")) {
3811
+ return "Checking your connected apps";
3812
+ }
3813
+ if (n.includes("search")) return "Searching the web";
3814
+ if (n.includes("calendar") || n.includes("event")) {
3815
+ return "Checking your calendar";
3816
+ }
3817
+ if (n.includes("email") || n.includes("gmail")) return "Reading your email";
3818
+ if (n.includes("memor")) return "Remembering";
3819
+ if (n.includes("opus") || n.includes("reason")) return "Thinking it through";
3820
+ if (n.includes("composio")) return "Using a connected app";
3821
+ if (n.includes("send_to_device") || n.includes("computer")) {
3822
+ return "Handing this to your computer";
3823
+ }
3824
+ if (n.includes("title")) return "Naming the conversation";
3825
+ if (n.includes("document") || n.includes("doc")) return "Working on a document";
3826
+ return "Working on it";
3827
+ };
3828
+ stepDetail = (frame) => {
3829
+ const text = frame.responseToUser ?? "";
3830
+ const links = text.match(/\]\(https?:\/\//g)?.length ?? 0;
3831
+ if (links) return `${links} ${links === 1 ? "result" : "results"}`;
3832
+ return frame.toolOutcome?.summary?.split("\n")[0].slice(0, 90) ?? "";
3833
+ };
3803
3834
  errorText = (value) => {
3804
3835
  if (typeof value === "string") return value;
3805
3836
  if (value && typeof value === "object" && "message" in value) {
@@ -3807,149 +3838,511 @@ var init_chat = __esm({
3807
3838
  }
3808
3839
  return value ? JSON.stringify(value) : "";
3809
3840
  };
3810
- sendMessage = (config2, conversation, prompt, onWord = () => {
3811
- }, onStep = () => {
3812
- }, timeoutMs = 10 * 60 * 1e3) => new Promise((resolve, reject) => {
3813
- const url = config2.baseUrl.replace(/^http/, "ws") + `/odyssey/ws?threadId=${encodeURIComponent(conversation.threadId)}`;
3814
- const socket = new wrapper_default(url, {
3815
- headers: {
3816
- Cookie: `session_token=${config2.token}`,
3817
- Origin: config2.baseUrl
3818
- }
3819
- });
3820
- const requestId = (0, import_crypto2.randomUUID)();
3821
- const started = Date.now();
3822
- let firstWord = 0;
3823
- let settled = false;
3824
- const finish = (error, text = "") => {
3825
- if (settled) return;
3826
- settled = true;
3827
- clearTimeout(timer);
3828
- socket.close();
3829
- if (error) reject(error);
3830
- else {
3831
- resolve({
3832
- text,
3833
- firstWord: (firstWord || Date.now() - started) / 1e3,
3834
- total: (Date.now() - started) / 1e3
3835
- });
3836
- }
3841
+ startTurn = (config2, conversation, prompt, listeners2 = {}, timeoutMs = 10 * 60 * 1e3) => {
3842
+ let stop = () => {
3837
3843
  };
3838
- const timer = setTimeout(() => {
3839
- try {
3844
+ const reply = new Promise((resolve, reject) => {
3845
+ const url = config2.baseUrl.replace(/^http/, "ws") + `/odyssey/ws?threadId=${encodeURIComponent(conversation.threadId)}`;
3846
+ const socket = new wrapper_default(url, {
3847
+ headers: {
3848
+ Cookie: `session_token=${config2.token}`,
3849
+ Origin: config2.baseUrl
3850
+ }
3851
+ });
3852
+ const requestId = (0, import_crypto2.randomUUID)();
3853
+ const started = Date.now();
3854
+ let firstWord = 0;
3855
+ let settled = false;
3856
+ const finish = (error, text = "") => {
3857
+ if (settled) return;
3858
+ settled = true;
3859
+ clearTimeout(timer);
3860
+ socket.close();
3861
+ if (error) reject(error);
3862
+ else {
3863
+ resolve({
3864
+ text,
3865
+ firstWord: (firstWord || Date.now() - started) / 1e3,
3866
+ total: (Date.now() - started) / 1e3
3867
+ });
3868
+ }
3869
+ };
3870
+ const cancel = () => {
3871
+ try {
3872
+ socket.send(
3873
+ JSON.stringify({
3874
+ requestType: "cancelTurn",
3875
+ odysseyRequest: { threadId: conversation.threadId }
3876
+ })
3877
+ );
3878
+ } catch {
3879
+ }
3880
+ };
3881
+ stop = () => {
3882
+ cancel();
3883
+ finish(new StoppedError());
3884
+ };
3885
+ const timer = setTimeout(() => {
3886
+ cancel();
3887
+ finish(new CliError("No reply in time. Try again."));
3888
+ }, timeoutMs);
3889
+ socket.on("open", () => {
3840
3890
  socket.send(
3841
3891
  JSON.stringify({
3842
- requestType: "cancelTurn",
3843
- odysseyRequest: { threadId: conversation.threadId }
3892
+ requestType: "text",
3893
+ odysseyRequest: {
3894
+ id: requestId,
3895
+ version: conversation.version,
3896
+ userId: config2.userId,
3897
+ threadId: conversation.threadId,
3898
+ documentId: null,
3899
+ requestType: "unknown",
3900
+ requestPrompt: { prompt, context: [] },
3901
+ userMessageId: (0, import_crypto2.randomUUID)(),
3902
+ userContext: { userId: config2.userId },
3903
+ odysseyContext: {
3904
+ currentDateTime: (/* @__PURE__ */ new Date()).toISOString(),
3905
+ mode: conversation.mode,
3906
+ planningContext: {
3907
+ threadId: conversation.threadId,
3908
+ ...conversation.workspaceId ? { workspaceId: conversation.workspaceId } : {}
3909
+ }
3910
+ },
3911
+ mode: conversation.mode
3912
+ }
3844
3913
  })
3845
3914
  );
3846
- } catch {
3847
- }
3848
- finish(new CliError("No reply in time. Try again."));
3849
- }, timeoutMs);
3850
- socket.on("open", () => {
3851
- socket.send(
3852
- JSON.stringify({
3853
- requestType: "text",
3854
- odysseyRequest: {
3855
- id: requestId,
3856
- version: conversation.version,
3857
- userId: config2.userId,
3858
- threadId: conversation.threadId,
3859
- documentId: null,
3860
- requestType: "unknown",
3861
- requestPrompt: { prompt, context: [] },
3862
- userMessageId: (0, import_crypto2.randomUUID)(),
3863
- userContext: { userId: config2.userId },
3864
- odysseyContext: {
3865
- currentDateTime: (/* @__PURE__ */ new Date()).toISOString(),
3866
- mode: conversation.mode,
3867
- planningContext: {
3868
- threadId: conversation.threadId,
3869
- ...conversation.workspaceId ? { workspaceId: conversation.workspaceId } : {}
3870
- }
3871
- },
3872
- mode: conversation.mode
3873
- }
3874
- })
3915
+ });
3916
+ socket.on("message", (raw) => {
3917
+ let frame;
3918
+ try {
3919
+ frame = JSON.parse(String(raw));
3920
+ } catch {
3921
+ return;
3922
+ }
3923
+ if (frame.messageType === "outputPartialTranscription" && frame.streamingWord) {
3924
+ firstWord ||= Date.now() - started;
3925
+ listeners2.onWord?.(frame.streamingWord);
3926
+ } else if (frame.messageType === "toolCall" && frame.toolFunctionName) {
3927
+ listeners2.onStep?.({
3928
+ label: stepLabel(frame.toolFunctionName),
3929
+ detail: stepDetail(frame),
3930
+ failed: frame.toolOutcome?.state === "error" || frame.toolOutcome?.state === "failed"
3931
+ });
3932
+ } else if (frame.messageType === "openClawThinking" && frame.openClawThinking?.text) {
3933
+ listeners2.onThinking?.(
3934
+ frame.openClawThinking.text,
3935
+ !!frame.openClawThinking.reset
3936
+ );
3937
+ } else if (frame.messageType === "assistantMessage" && frame.responseToUser?.trim()) {
3938
+ finish(null, frame.responseToUser);
3939
+ } else if (frame.messageType === "error" && errorText(frame.error)) {
3940
+ finish(new CliError(errorText(frame.error)));
3941
+ } else if (frame.textStreamError) {
3942
+ finish(new CliError(errorText(frame.textStreamError)));
3943
+ } else if (frame.activeTurn?.status === "idle" && frame.activeTurn.runId === requestId) {
3944
+ finish(new CliError("Clox finished without a reply. Try again."));
3945
+ }
3946
+ });
3947
+ socket.on(
3948
+ "error",
3949
+ () => finish(new CliError(`Could not reach Clox at ${config2.baseUrl}.`))
3950
+ );
3951
+ socket.on(
3952
+ "close",
3953
+ () => finish(new CliError("The connection closed before a reply."))
3875
3954
  );
3876
3955
  });
3877
- socket.on("message", (raw) => {
3878
- let frame;
3879
- try {
3880
- frame = JSON.parse(String(raw));
3881
- } catch {
3882
- return;
3883
- }
3884
- if (frame.messageType === "outputPartialTranscription" && frame.streamingWord) {
3885
- firstWord ||= Date.now() - started;
3886
- onWord(frame.streamingWord);
3887
- } else if (frame.messageType === "toolCall") {
3888
- const what = frame.toolOutcome?.summary || frame.toolFunctionName || "";
3889
- if (what) onStep(what);
3890
- } else if (frame.messageType === "openClawThinking" && frame.openClawThinking?.text?.trim()) {
3891
- onStep(frame.openClawThinking.text.trim().split("\n")[0]);
3892
- } else if (frame.messageType === "assistantMessage" && frame.responseToUser?.trim()) {
3893
- finish(null, frame.responseToUser);
3894
- } else if (frame.messageType === "error" && errorText(frame.error)) {
3895
- finish(new CliError(errorText(frame.error)));
3896
- } else if (frame.textStreamError) {
3897
- finish(new CliError(errorText(frame.textStreamError)));
3898
- } else if (frame.activeTurn?.status === "idle" && frame.activeTurn.runId === requestId) {
3899
- finish(new CliError("Clox finished without a reply. Try again."));
3900
- }
3901
- });
3902
- socket.on(
3903
- "error",
3904
- () => finish(new CliError(`Could not reach Clox at ${config2.baseUrl}.`))
3905
- );
3906
- socket.on(
3907
- "close",
3908
- () => finish(new CliError("The connection closed before a reply."))
3909
- );
3910
- });
3956
+ return { reply, stop: () => stop() };
3957
+ };
3958
+ StoppedError = class extends Error {
3959
+ constructor() {
3960
+ super("Stopped.");
3961
+ }
3962
+ };
3963
+ sendMessage = (config2, conversation, prompt, listeners2 = {}) => startTurn(config2, conversation, prompt, listeners2).reply;
3911
3964
  say = async (config2, conversation, prompt) => {
3912
3965
  let streamed = false;
3913
- const reply = await sendMessage(
3914
- config2,
3915
- conversation,
3916
- prompt,
3917
- (word) => {
3966
+ const reply = await sendMessage(config2, conversation, prompt, {
3967
+ onWord: (word) => {
3918
3968
  streamed = true;
3919
3969
  process.stdout.write(word);
3920
3970
  },
3921
- (step) => {
3922
- if (!streamed) console.log(dim(` ${step.slice(0, 100)}`));
3971
+ onStep: (step) => {
3972
+ if (!streamed) console.error(dim(` ${step.label}`));
3923
3973
  }
3924
- );
3974
+ });
3925
3975
  if (streamed) process.stdout.write("\n");
3926
3976
  else console.log(reply.text);
3927
3977
  return reply;
3928
3978
  };
3929
- converse = async (config2, conversation, title) => {
3930
- console.log(`${bold(title)} ${dim("(/exit or Ctrl-D to leave)")}
3979
+ }
3980
+ });
3981
+
3982
+ // src/tui.ts
3983
+ var tui_exports = {};
3984
+ __export(tui_exports, {
3985
+ chatScreen: () => chatScreen,
3986
+ markdown: () => markdown,
3987
+ wrap: () => wrap
3988
+ });
3989
+ var import_crypto3, ESC, color, dim2, bold2, accent, soft, good, bad, userBg, SPINNER, width, wrap, markdown, thoughtTitle, credits, chatScreen;
3990
+ var init_tui = __esm({
3991
+ "src/tui.ts"() {
3992
+ "use strict";
3993
+ import_crypto3 = require("crypto");
3994
+ init_api();
3995
+ init_chat();
3996
+ init_logo();
3997
+ ESC = "\x1B[";
3998
+ color = (code) => (text) => `${ESC}${code}m${text}${ESC}0m`;
3999
+ dim2 = color("2");
4000
+ bold2 = color("1");
4001
+ accent = color("38;5;111");
4002
+ soft = color("38;5;245");
4003
+ good = color("38;5;114");
4004
+ bad = color("38;5;203");
4005
+ userBg = color("48;5;236");
4006
+ SPINNER = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
4007
+ width = (text) => [...text.replace(/\x1b\[[0-9;]*m/g, "")].length;
4008
+ wrap = (text, max) => {
4009
+ const out = [];
4010
+ for (const raw of text.split("\n")) {
4011
+ let line = "";
4012
+ for (const word of raw.split(/(\s+)/)) {
4013
+ if (width(line + word) <= max) {
4014
+ line += word;
4015
+ continue;
4016
+ }
4017
+ if (line.trim()) out.push(line.trimEnd());
4018
+ line = word.trimStart();
4019
+ while (width(line) > max) {
4020
+ const parts = line.match(/\x1b\[[0-9;]*m|[^\x1b]/gu) ?? [];
4021
+ let shown = 0;
4022
+ let cut = 0;
4023
+ for (; cut < parts.length && shown < max; cut += 1) {
4024
+ if (!parts[cut].startsWith("\x1B")) shown += 1;
4025
+ }
4026
+ out.push(parts.slice(0, cut).join(""));
4027
+ line = parts.slice(cut).join("");
4028
+ }
4029
+ }
4030
+ out.push(line.trimEnd());
4031
+ }
4032
+ return out;
4033
+ };
4034
+ markdown = (text) => text.split("\n").map((line) => {
4035
+ const heading = line.match(/^#{1,6}\s+(.*)$/);
4036
+ if (heading) return bold2(heading[1]);
4037
+ return line.replace(
4038
+ /\[([^[\]]+)\]\((https?:[^)\s]+)\)/g,
4039
+ (_, t, u) => `${t} ${soft(u)}`
4040
+ ).replace(/^(\s*)[-*]\s+/, "$1\u2022 ").replace(/\*\*([^*]+)\*\*/g, (_, b) => bold2(b)).replace(/`([^`]+)`/g, (_, c) => accent(c));
4041
+ }).join("\n");
4042
+ thoughtTitle = (thinking) => {
4043
+ const heading = thinking.match(/\*\*([^*]+)\*\*/);
4044
+ if (heading) return heading[1].trim();
4045
+ return "";
4046
+ };
4047
+ credits = async (config2) => {
4048
+ try {
4049
+ const data = await gql(
4050
+ config2,
4051
+ "query CliCredits { creditsState { balance } }"
4052
+ );
4053
+ return data.creditsState.balance;
4054
+ } catch {
4055
+ return null;
4056
+ }
4057
+ };
4058
+ chatScreen = async (config2, conversation, title, firstMessage = "") => {
4059
+ const out = process.stdout;
4060
+ const input = process.stdin;
4061
+ if (!input.isTTY || !out.isTTY) {
4062
+ throw new CliError("The conversation needs a terminal.");
4063
+ }
4064
+ let draft = "";
4065
+ let cursor = 0;
4066
+ const history = [];
4067
+ let historyAt = -1;
4068
+ let turn = null;
4069
+ let started = 0;
4070
+ let thinking = "";
4071
+ let streaming = "";
4072
+ let frame = 0;
4073
+ let balance = null;
4074
+ let lastTime = "";
4075
+ const queued = [];
4076
+ let liveLines = 0;
4077
+ let quitArmed = false;
4078
+ const columns = () => Math.max(40, out.columns || 80);
4079
+ const live = () => {
4080
+ const cols = columns();
4081
+ const lines = [];
4082
+ if (turn) {
4083
+ if (streaming) {
4084
+ const room2 = Math.max(4, (out.rows || 24) - 10);
4085
+ const body = wrap(markdown(streaming), cols - 2).map((l) => ` ${l}`);
4086
+ lines.push(...body.slice(-room2));
4087
+ }
4088
+ const seconds = Math.floor((Date.now() - started) / 1e3);
4089
+ const doing = (thoughtTitle(thinking) || (streaming ? "Writing" : "Thinking")).slice(0, cols - 28);
4090
+ lines.push(
4091
+ `${accent(SPINNER[frame % SPINNER.length])} ${doing}\u2026 ` + soft(`(${seconds}s \xB7 esc to stop)`)
4092
+ );
4093
+ if (queued.length) {
4094
+ lines.push(soft(` ${queued.length} message waiting to send`));
4095
+ }
4096
+ lines.push("");
4097
+ }
4098
+ const inner = cols - 4;
4099
+ const shown = draft || "";
4100
+ const placeholder = turn ? "Type your next message" : "Ask anything";
4101
+ const text = shown ? wrap(shown, inner - 2) : [soft(placeholder)];
4102
+ lines.push(soft(`\u256D${"\u2500".repeat(cols - 2)}\u256E`));
4103
+ text.forEach((line, i) => {
4104
+ const lead = i === 0 ? `${accent(">")} ` : " ";
4105
+ lines.push(
4106
+ `${soft("\u2502")} ${lead}${line}${" ".repeat(Math.max(0, inner - 2 - width(line)))} ${soft("\u2502")}`
4107
+ );
4108
+ });
4109
+ lines.push(soft(`\u2570${"\u2500".repeat(cols - 2)}\u256F`));
4110
+ const left = [
4111
+ title,
4112
+ balance === null ? "" : `${balance.toLocaleString("en-US")} credits`,
4113
+ lastTime ? `last reply ${lastTime}` : ""
4114
+ ].filter(Boolean).join(" \xB7 ");
4115
+ const right = quitArmed ? "Press Ctrl-C again to leave" : turn ? "esc stop \xB7 ctrl-c leave" : "\u21B5 send \xB7 /help \xB7 ctrl-c leave";
4116
+ const room = cols - 2 - width(right) - 1;
4117
+ const shortLeft = width(left) > room ? left.slice(0, Math.max(0, room - 1)) + "\u2026" : left;
4118
+ const gap = Math.max(1, cols - 2 - width(shortLeft) - width(right));
4119
+ lines.push(soft(` ${shortLeft}${" ".repeat(gap)}${right}`));
4120
+ return lines;
4121
+ };
4122
+ const cursorFor = () => {
4123
+ const inner = columns() - 4;
4124
+ const before = wrap(draft.slice(0, cursor) || "", inner - 2);
4125
+ const row = before.length - 1;
4126
+ const col = width(before[before.length - 1] ?? "");
4127
+ const boxLines = draft ? wrap(draft, inner - 2).length : 1;
4128
+ return { rows: 2 + (boxLines - 1 - row), col: 4 + col };
4129
+ };
4130
+ let cursorUp = 0;
4131
+ const clearCodes = () => {
4132
+ let codes = "";
4133
+ if (cursorUp) codes += `${ESC}${cursorUp}B`;
4134
+ cursorUp = 0;
4135
+ if (liveLines > 1) codes += `\r${ESC}${liveLines - 1}A`;
4136
+ liveLines = 0;
4137
+ return `${codes}\r${ESC}J`;
4138
+ };
4139
+ const clearLive = () => {
4140
+ out.write(clearCodes());
4141
+ };
4142
+ const draw = (above = "") => {
4143
+ const lines = live();
4144
+ const up = cursorFor();
4145
+ out.write(
4146
+ clearCodes() + above + lines.join("\n") + `${ESC}${up.rows}A\r${ESC}${up.col}C`
4147
+ );
4148
+ liveLines = lines.length;
4149
+ cursorUp = up.rows;
4150
+ };
4151
+ const print3 = (text) => draw(`${text}
3931
4152
  `);
3932
- const terminal = import_readline.default.createInterface({
3933
- input: process.stdin,
3934
- output: process.stdout
3935
- });
3936
- const ask = () => new Promise((resolve) => {
3937
- terminal.once("close", () => resolve(null));
3938
- terminal.question(bold("> "), (line) => resolve(line));
3939
- });
3940
- for (; ; ) {
3941
- const line = await ask();
3942
- if (line === null || /^\/(exit|quit)$/.test(line.trim())) break;
3943
- if (!line.trim()) continue;
4153
+ const send = async (message) => {
4154
+ print3(`
4155
+ ${userBg(` > ${message} `)}
4156
+ `);
4157
+ thinking = "";
4158
+ streaming = "";
4159
+ started = Date.now();
4160
+ turn = startTurn(config2, conversation, message, {
4161
+ onWord: (word) => {
4162
+ streaming += word;
4163
+ },
4164
+ onThinking: (text, reset) => {
4165
+ thinking = reset ? text : thinking + text;
4166
+ },
4167
+ onStep: (step) => {
4168
+ const mark = step.failed ? bad("\u23FA") : good("\u23FA");
4169
+ const detail = step.detail ? `
4170
+ ${soft(`\u23BF ${step.detail}`)}` : "";
4171
+ print3(`${mark} ${bold2(step.label)}${detail}`);
4172
+ }
4173
+ });
3944
4174
  try {
3945
- console.log();
3946
- await say(config2, conversation, line.trim());
3947
- console.log();
4175
+ const reply = await turn.reply;
4176
+ turn = null;
4177
+ lastTime = `${reply.total.toFixed(1)}s`;
4178
+ print3(`
4179
+ ${accent("\u23FA")} ${wrap(markdown(reply.text), columns() - 2).join("\n ")}`);
3948
4180
  } catch (error) {
3949
- console.error(red(error instanceof Error ? error.message : String(error)));
3950
- }
4181
+ turn = null;
4182
+ if (error instanceof StoppedError) {
4183
+ const sofar = streaming.trim() ? `
4184
+ ${accent("\u23FA")} ${wrap(markdown(streaming), columns() - 2).join("\n ")}
4185
+ ` : "";
4186
+ print3(`${sofar}${soft(" Stopped.")}`);
4187
+ } else print3(bad(` ${error instanceof Error ? error.message : String(error)}`));
4188
+ }
4189
+ streaming = "";
4190
+ thinking = "";
4191
+ void credits(config2).then((value) => {
4192
+ balance = value;
4193
+ draw();
4194
+ });
4195
+ const next = queued.shift();
4196
+ if (next) void send(next);
4197
+ else draw();
4198
+ };
4199
+ const help = () => {
4200
+ print3(
4201
+ [
4202
+ "",
4203
+ bold2("Keys"),
4204
+ " Enter send",
4205
+ " Esc stop the reply",
4206
+ " Up / Down earlier messages",
4207
+ " Ctrl-U clear what you typed",
4208
+ " Ctrl-C leave (twice)",
4209
+ "",
4210
+ bold2("Commands"),
4211
+ " /new start a new conversation",
4212
+ " /exit leave",
4213
+ ""
4214
+ ].join("\n")
4215
+ );
4216
+ };
4217
+ let done = () => {
4218
+ };
4219
+ const finished = new Promise((resolve) => {
4220
+ done = resolve;
4221
+ });
4222
+ const leave = () => {
4223
+ turn?.stop();
4224
+ clearLive();
4225
+ clearInterval(ticker);
4226
+ input.setRawMode(false);
4227
+ input.pause();
4228
+ input.removeListener("data", onData);
4229
+ out.removeListener("resize", onResize);
4230
+ out.write("\n");
4231
+ done();
4232
+ };
4233
+ const submit = () => {
4234
+ const message = draft.trim();
4235
+ draft = "";
4236
+ cursor = 0;
4237
+ historyAt = -1;
4238
+ if (!message) return draw();
4239
+ if (message === "/exit" || message === "/quit") return leave();
4240
+ if (message === "/help") return help();
4241
+ if (message === "/new") {
4242
+ conversation.threadId = (0, import_crypto3.randomUUID)();
4243
+ return print3(soft(" A new conversation."));
4244
+ }
4245
+ history.unshift(message);
4246
+ if (turn) {
4247
+ queued.push(message);
4248
+ return draw();
4249
+ }
4250
+ void send(message);
4251
+ };
4252
+ const onData = (chunk) => {
4253
+ const key = chunk.toString("utf8");
4254
+ if (key !== "") quitArmed = false;
4255
+ switch (key) {
4256
+ case "":
4257
+ if (draft) {
4258
+ draft = "";
4259
+ cursor = 0;
4260
+ } else if (quitArmed) {
4261
+ return leave();
4262
+ } else {
4263
+ quitArmed = true;
4264
+ }
4265
+ return draw();
4266
+ case "":
4267
+ if (!draft) return leave();
4268
+ return;
4269
+ case "\x1B":
4270
+ if (turn) turn.stop();
4271
+ return;
4272
+ case "\r":
4273
+ case "\n":
4274
+ return submit();
4275
+ case "\x7F":
4276
+ case "\b":
4277
+ if (cursor > 0) {
4278
+ draft = draft.slice(0, cursor - 1) + draft.slice(cursor);
4279
+ cursor -= 1;
4280
+ }
4281
+ return draw();
4282
+ case "":
4283
+ draft = "";
4284
+ cursor = 0;
4285
+ return draw();
4286
+ case "":
4287
+ cursor = 0;
4288
+ return draw();
4289
+ case "":
4290
+ cursor = draft.length;
4291
+ return draw();
4292
+ case `${ESC}D`:
4293
+ cursor = Math.max(0, cursor - 1);
4294
+ return draw();
4295
+ case `${ESC}C`:
4296
+ cursor = Math.min(draft.length, cursor + 1);
4297
+ return draw();
4298
+ case `${ESC}A`:
4299
+ if (historyAt + 1 < history.length) {
4300
+ historyAt += 1;
4301
+ draft = history[historyAt];
4302
+ cursor = draft.length;
4303
+ }
4304
+ return draw();
4305
+ case `${ESC}B`:
4306
+ historyAt = Math.max(-1, historyAt - 1);
4307
+ draft = historyAt < 0 ? "" : history[historyAt];
4308
+ cursor = draft.length;
4309
+ return draw();
4310
+ }
4311
+ if (key.startsWith("\x1B")) return;
4312
+ const text = key.replace(/[\r\n]+/g, " ").replace(/[\x00-\x1f]/g, "");
4313
+ if (!text) return;
4314
+ draft = draft.slice(0, cursor) + text + draft.slice(cursor);
4315
+ cursor += text.length;
4316
+ draw();
4317
+ };
4318
+ const onResize = () => draw();
4319
+ out.write(`${logo()}
4320
+
4321
+ `);
4322
+ out.write(
4323
+ `${bold2(title)} ${soft(`signed in as ${config2.signedInAs || "you"}`)}
4324
+ `
4325
+ );
4326
+ out.write(soft("Type a message and press Enter. /help for keys.\n"));
4327
+ input.setRawMode(true);
4328
+ input.resume();
4329
+ input.on("data", onData);
4330
+ out.on("resize", onResize);
4331
+ const ticker = setInterval(() => {
4332
+ if (!turn) return;
4333
+ frame += 1;
4334
+ draw();
4335
+ }, 100);
4336
+ draw();
4337
+ void credits(config2).then((value) => {
4338
+ balance = value;
4339
+ draw();
4340
+ });
4341
+ if (firstMessage.trim()) {
4342
+ history.unshift(firstMessage.trim());
4343
+ void send(firstMessage.trim());
3951
4344
  }
3952
- terminal.close();
4345
+ await finished;
3953
4346
  };
3954
4347
  }
3955
4348
  });
@@ -4033,12 +4426,12 @@ var init_electron_shim = __esm({
4033
4426
  });
4034
4427
  child2.unref();
4035
4428
  };
4036
- grabScreen = (width, height) => {
4429
+ grabScreen = (width2, height) => {
4037
4430
  try {
4038
4431
  if (process.platform === "darwin") {
4039
4432
  const file = import_path3.default.join(import_os2.default.tmpdir(), `clox-screen-${process.pid}.jpg`);
4040
4433
  (0, import_child_process2.execFileSync)("screencapture", ["-x", "-t", "jpg", file]);
4041
- (0, import_child_process2.execFileSync)("sips", ["-z", String(height), String(width), file], {
4434
+ (0, import_child_process2.execFileSync)("sips", ["-z", String(height), String(width2), file], {
4042
4435
  stdio: "ignore"
4043
4436
  });
4044
4437
  const data = import_fs3.default.readFileSync(file);
@@ -4051,7 +4444,7 @@ var init_electron_shim = __esm({
4051
4444
  "-window",
4052
4445
  "root",
4053
4446
  "-resize",
4054
- `${width}x${height}!`,
4447
+ `${width2}x${height}!`,
4055
4448
  "-quality",
4056
4449
  "70",
4057
4450
  "jpg:-"
@@ -4062,10 +4455,10 @@ var init_electron_shim = __esm({
4062
4455
  return Buffer.alloc(0);
4063
4456
  }
4064
4457
  };
4065
- picture = (data, width, height) => {
4458
+ picture = (data, width2, height) => {
4066
4459
  const self2 = {
4067
4460
  isEmpty: () => data.length === 0,
4068
- getSize: () => ({ width, height }),
4461
+ getSize: () => ({ width: width2, height }),
4069
4462
  resize: () => self2,
4070
4463
  toJPEG: () => data,
4071
4464
  toPNG: () => data
@@ -4118,7 +4511,7 @@ var init_electron_shim = __esm({
4118
4511
  missingInput = () => {
4119
4512
  const fail2 = () => {
4120
4513
  throw new Error(
4121
- "This computer cannot move the pointer or type for Clox: the input library is not installed (npm install -g clox installs it)."
4514
+ "This computer cannot move the pointer or type for Clox: the input library is not installed (npm install -g @cloxco/clox installs it)."
4122
4515
  );
4123
4516
  };
4124
4517
  const anything = new Proxy(fail2, {
@@ -8869,8 +9262,8 @@ var require_printer = __commonJS({
8869
9262
  },
8870
9263
  OperationDefinition: {
8871
9264
  leave(node) {
8872
- const varDefs = hasMultilineItems(node.variableDefinitions) ? wrap2("(\n", join2(node.variableDefinitions, "\n"), "\n)") : wrap2("(", join2(node.variableDefinitions, ", "), ")");
8873
- const prefix = wrap2("", node.description, "\n") + join2(
9265
+ const varDefs = hasMultilineItems(node.variableDefinitions) ? wrap3("(\n", join2(node.variableDefinitions, "\n"), "\n)") : wrap3("(", join2(node.variableDefinitions, ", "), ")");
9266
+ const prefix = wrap3("", node.description, "\n") + join2(
8874
9267
  [
8875
9268
  node.operation,
8876
9269
  join2([node.name, varDefs]),
@@ -8882,17 +9275,17 @@ var require_printer = __commonJS({
8882
9275
  }
8883
9276
  },
8884
9277
  VariableDefinition: {
8885
- leave: ({ variable, type, defaultValue, directives, description }) => wrap2("", description, "\n") + variable + ": " + type + wrap2(" = ", defaultValue) + wrap2(" ", join2(directives, " "))
9278
+ leave: ({ variable, type, defaultValue, directives, description }) => wrap3("", description, "\n") + variable + ": " + type + wrap3(" = ", defaultValue) + wrap3(" ", join2(directives, " "))
8886
9279
  },
8887
9280
  SelectionSet: {
8888
9281
  leave: ({ selections }) => block(selections)
8889
9282
  },
8890
9283
  Field: {
8891
9284
  leave({ alias, name: name5, arguments: args, directives, selectionSet }) {
8892
- const prefix = wrap2("", alias, ": ") + name5;
8893
- let argsLine = prefix + wrap2("(", join2(args, ", "), ")");
9285
+ const prefix = wrap3("", alias, ": ") + name5;
9286
+ let argsLine = prefix + wrap3("(", join2(args, ", "), ")");
8894
9287
  if (argsLine.length > MAX_LINE_LENGTH) {
8895
- argsLine = prefix + wrap2("(\n", indent(join2(args, "\n")), "\n)");
9288
+ argsLine = prefix + wrap3("(\n", indent(join2(args, "\n")), "\n)");
8896
9289
  }
8897
9290
  return join2([argsLine, join2(directives, " "), selectionSet], " ");
8898
9291
  }
@@ -8902,13 +9295,13 @@ var require_printer = __commonJS({
8902
9295
  },
8903
9296
  // Fragments
8904
9297
  FragmentSpread: {
8905
- leave: ({ name: name5, directives }) => "..." + name5 + wrap2(" ", join2(directives, " "))
9298
+ leave: ({ name: name5, directives }) => "..." + name5 + wrap3(" ", join2(directives, " "))
8906
9299
  },
8907
9300
  InlineFragment: {
8908
9301
  leave: ({ typeCondition, directives, selectionSet }) => join2(
8909
9302
  [
8910
9303
  "...",
8911
- wrap2("on ", typeCondition),
9304
+ wrap3("on ", typeCondition),
8912
9305
  join2(directives, " "),
8913
9306
  selectionSet
8914
9307
  ],
@@ -8923,9 +9316,9 @@ var require_printer = __commonJS({
8923
9316
  directives,
8924
9317
  selectionSet,
8925
9318
  description
8926
- }) => wrap2("", description, "\n") + // Note: fragment variable definitions are experimental and may be changed
9319
+ }) => wrap3("", description, "\n") + // Note: fragment variable definitions are experimental and may be changed
8927
9320
  // or removed in the future.
8928
- `fragment ${name5}${wrap2("(", join2(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap2("", join2(directives, " "), " ")}` + selectionSet
9321
+ `fragment ${name5}${wrap3("(", join2(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap3("", join2(directives, " "), " ")}` + selectionSet
8929
9322
  },
8930
9323
  // Value
8931
9324
  IntValue: {
@@ -8957,7 +9350,7 @@ var require_printer = __commonJS({
8957
9350
  },
8958
9351
  // Directive
8959
9352
  Directive: {
8960
- leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap2("(", join2(args, ", "), ")")
9353
+ leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap3("(", join2(args, ", "), ")")
8961
9354
  },
8962
9355
  // Type
8963
9356
  NamedType: {
@@ -8971,20 +9364,20 @@ var require_printer = __commonJS({
8971
9364
  },
8972
9365
  // Type System Definitions
8973
9366
  SchemaDefinition: {
8974
- leave: ({ description, directives, operationTypes }) => wrap2("", description, "\n") + join2(["schema", join2(directives, " "), block(operationTypes)], " ")
9367
+ leave: ({ description, directives, operationTypes }) => wrap3("", description, "\n") + join2(["schema", join2(directives, " "), block(operationTypes)], " ")
8975
9368
  },
8976
9369
  OperationTypeDefinition: {
8977
9370
  leave: ({ operation, type }) => operation + ": " + type
8978
9371
  },
8979
9372
  ScalarTypeDefinition: {
8980
- leave: ({ description, name: name5, directives }) => wrap2("", description, "\n") + join2(["scalar", name5, join2(directives, " ")], " ")
9373
+ leave: ({ description, name: name5, directives }) => wrap3("", description, "\n") + join2(["scalar", name5, join2(directives, " ")], " ")
8981
9374
  },
8982
9375
  ObjectTypeDefinition: {
8983
- leave: ({ description, name: name5, interfaces, directives, fields }) => wrap2("", description, "\n") + join2(
9376
+ leave: ({ description, name: name5, interfaces, directives, fields }) => wrap3("", description, "\n") + join2(
8984
9377
  [
8985
9378
  "type",
8986
9379
  name5,
8987
- wrap2("implements ", join2(interfaces, " & ")),
9380
+ wrap3("implements ", join2(interfaces, " & ")),
8988
9381
  join2(directives, " "),
8989
9382
  block(fields)
8990
9383
  ],
@@ -8992,20 +9385,20 @@ var require_printer = __commonJS({
8992
9385
  )
8993
9386
  },
8994
9387
  FieldDefinition: {
8995
- leave: ({ description, name: name5, arguments: args, type, directives }) => wrap2("", description, "\n") + name5 + (hasMultilineItems(args) ? wrap2("(\n", indent(join2(args, "\n")), "\n)") : wrap2("(", join2(args, ", "), ")")) + ": " + type + wrap2(" ", join2(directives, " "))
9388
+ leave: ({ description, name: name5, arguments: args, type, directives }) => wrap3("", description, "\n") + name5 + (hasMultilineItems(args) ? wrap3("(\n", indent(join2(args, "\n")), "\n)") : wrap3("(", join2(args, ", "), ")")) + ": " + type + wrap3(" ", join2(directives, " "))
8996
9389
  },
8997
9390
  InputValueDefinition: {
8998
- leave: ({ description, name: name5, type, defaultValue, directives }) => wrap2("", description, "\n") + join2(
8999
- [name5 + ": " + type, wrap2("= ", defaultValue), join2(directives, " ")],
9391
+ leave: ({ description, name: name5, type, defaultValue, directives }) => wrap3("", description, "\n") + join2(
9392
+ [name5 + ": " + type, wrap3("= ", defaultValue), join2(directives, " ")],
9000
9393
  " "
9001
9394
  )
9002
9395
  },
9003
9396
  InterfaceTypeDefinition: {
9004
- leave: ({ description, name: name5, interfaces, directives, fields }) => wrap2("", description, "\n") + join2(
9397
+ leave: ({ description, name: name5, interfaces, directives, fields }) => wrap3("", description, "\n") + join2(
9005
9398
  [
9006
9399
  "interface",
9007
9400
  name5,
9008
- wrap2("implements ", join2(interfaces, " & ")),
9401
+ wrap3("implements ", join2(interfaces, " & ")),
9009
9402
  join2(directives, " "),
9010
9403
  block(fields)
9011
9404
  ],
@@ -9013,19 +9406,19 @@ var require_printer = __commonJS({
9013
9406
  )
9014
9407
  },
9015
9408
  UnionTypeDefinition: {
9016
- leave: ({ description, name: name5, directives, types }) => wrap2("", description, "\n") + join2(
9017
- ["union", name5, join2(directives, " "), wrap2("= ", join2(types, " | "))],
9409
+ leave: ({ description, name: name5, directives, types }) => wrap3("", description, "\n") + join2(
9410
+ ["union", name5, join2(directives, " "), wrap3("= ", join2(types, " | "))],
9018
9411
  " "
9019
9412
  )
9020
9413
  },
9021
9414
  EnumTypeDefinition: {
9022
- leave: ({ description, name: name5, directives, values }) => wrap2("", description, "\n") + join2(["enum", name5, join2(directives, " "), block(values)], " ")
9415
+ leave: ({ description, name: name5, directives, values }) => wrap3("", description, "\n") + join2(["enum", name5, join2(directives, " "), block(values)], " ")
9023
9416
  },
9024
9417
  EnumValueDefinition: {
9025
- leave: ({ description, name: name5, directives }) => wrap2("", description, "\n") + join2([name5, join2(directives, " ")], " ")
9418
+ leave: ({ description, name: name5, directives }) => wrap3("", description, "\n") + join2([name5, join2(directives, " ")], " ")
9026
9419
  },
9027
9420
  InputObjectTypeDefinition: {
9028
- leave: ({ description, name: name5, directives, fields }) => wrap2("", description, "\n") + join2(["input", name5, join2(directives, " "), block(fields)], " ")
9421
+ leave: ({ description, name: name5, directives, fields }) => wrap3("", description, "\n") + join2(["input", name5, join2(directives, " "), block(fields)], " ")
9029
9422
  },
9030
9423
  DirectiveDefinition: {
9031
9424
  leave: ({
@@ -9035,7 +9428,7 @@ var require_printer = __commonJS({
9035
9428
  directives,
9036
9429
  repeatable,
9037
9430
  locations
9038
- }) => wrap2("", description, "\n") + "directive @" + name5 + (hasMultilineItems(args) ? wrap2("(\n", indent(join2(args, "\n")), "\n)") : wrap2("(", join2(args, ", "), ")")) + wrap2(" ", join2(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join2(locations, " | ")
9431
+ }) => wrap3("", description, "\n") + "directive @" + name5 + (hasMultilineItems(args) ? wrap3("(\n", indent(join2(args, "\n")), "\n)") : wrap3("(", join2(args, ", "), ")")) + wrap3(" ", join2(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join2(locations, " | ")
9039
9432
  },
9040
9433
  SchemaExtension: {
9041
9434
  leave: ({ directives, operationTypes }) => join2(
@@ -9051,7 +9444,7 @@ var require_printer = __commonJS({
9051
9444
  [
9052
9445
  "extend type",
9053
9446
  name5,
9054
- wrap2("implements ", join2(interfaces, " & ")),
9447
+ wrap3("implements ", join2(interfaces, " & ")),
9055
9448
  join2(directives, " "),
9056
9449
  block(fields)
9057
9450
  ],
@@ -9063,7 +9456,7 @@ var require_printer = __commonJS({
9063
9456
  [
9064
9457
  "extend interface",
9065
9458
  name5,
9066
- wrap2("implements ", join2(interfaces, " & ")),
9459
+ wrap3("implements ", join2(interfaces, " & ")),
9067
9460
  join2(directives, " "),
9068
9461
  block(fields)
9069
9462
  ],
@@ -9076,7 +9469,7 @@ var require_printer = __commonJS({
9076
9469
  "extend union",
9077
9470
  name5,
9078
9471
  join2(directives, " "),
9079
- wrap2("= ", join2(types, " | "))
9472
+ wrap3("= ", join2(types, " | "))
9080
9473
  ],
9081
9474
  " "
9082
9475
  )
@@ -9095,16 +9488,16 @@ var require_printer = __commonJS({
9095
9488
  leave: ({ name: name5 }) => name5
9096
9489
  },
9097
9490
  MemberCoordinate: {
9098
- leave: ({ name: name5, memberName }) => join2([name5, wrap2(".", memberName)])
9491
+ leave: ({ name: name5, memberName }) => join2([name5, wrap3(".", memberName)])
9099
9492
  },
9100
9493
  ArgumentCoordinate: {
9101
- leave: ({ name: name5, fieldName, argumentName }) => join2([name5, wrap2(".", fieldName), wrap2("(", argumentName, ":)")])
9494
+ leave: ({ name: name5, fieldName, argumentName }) => join2([name5, wrap3(".", fieldName), wrap3("(", argumentName, ":)")])
9102
9495
  },
9103
9496
  DirectiveCoordinate: {
9104
9497
  leave: ({ name: name5 }) => join2(["@", name5])
9105
9498
  },
9106
9499
  DirectiveArgumentCoordinate: {
9107
- leave: ({ name: name5, argumentName }) => join2(["@", name5, wrap2("(", argumentName, ":)")])
9500
+ leave: ({ name: name5, argumentName }) => join2(["@", name5, wrap3("(", argumentName, ":)")])
9108
9501
  }
9109
9502
  };
9110
9503
  function join2(maybeArray, separator = "") {
@@ -9112,13 +9505,13 @@ var require_printer = __commonJS({
9112
9505
  return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : "";
9113
9506
  }
9114
9507
  function block(array) {
9115
- return wrap2("{\n", indent(join2(array, "\n")), "\n}");
9508
+ return wrap3("{\n", indent(join2(array, "\n")), "\n}");
9116
9509
  }
9117
- function wrap2(start2, maybeString, end = "") {
9510
+ function wrap3(start2, maybeString, end = "") {
9118
9511
  return maybeString != null && maybeString !== "" ? start2 + maybeString + end : "";
9119
9512
  }
9120
9513
  function indent(str2) {
9121
- return wrap2(" ", str2.replace(/\n/g, "\n "));
9514
+ return wrap3(" ", str2.replace(/\n/g, "\n "));
9122
9515
  }
9123
9516
  function hasMultilineItems(maybeArray) {
9124
9517
  var _maybeArray$some;
@@ -22792,8 +23185,8 @@ var init_capabilities = __esm({
22792
23185
  return "";
22793
23186
  };
22794
23187
  geminiCliPath = async () => {
22795
- for (const shell2 of [["/bin/sh", "-lc"], ["/bin/zsh", "-lic"]]) {
22796
- const which = await probe(shell2[0], [shell2[1], "command -v gemini"]);
23188
+ for (const shell3 of [["/bin/sh", "-lc"], ["/bin/zsh", "-lic"]]) {
23189
+ const which = await probe(shell3[0], [shell3[1], "command -v gemini"]);
22797
23190
  const first = which.stdout.split("\n").map((l) => l.trim()).find((l) => l.startsWith("/"));
22798
23191
  if (which.code === 0 && first) return first;
22799
23192
  }
@@ -24132,12 +24525,12 @@ var init_types2 = __esm({
24132
24525
  });
24133
24526
 
24134
24527
  // ../desktop_ui/remote-host/claude-session.ts
24135
- var import_child_process5, import_crypto3, import_path11, TURN_TIMEOUT_MS, resultText, ClaudeSessionRunner;
24528
+ var import_child_process5, import_crypto4, import_path11, TURN_TIMEOUT_MS, resultText, ClaudeSessionRunner;
24136
24529
  var init_claude_session = __esm({
24137
24530
  "../desktop_ui/remote-host/claude-session.ts"() {
24138
24531
  "use strict";
24139
24532
  import_child_process5 = require("child_process");
24140
- import_crypto3 = require("crypto");
24533
+ import_crypto4 = require("crypto");
24141
24534
  import_path11 = __toESM(require("path"));
24142
24535
  init_capabilities();
24143
24536
  init_transcript_attach();
@@ -24170,7 +24563,7 @@ var init_claude_session = __esm({
24170
24563
  try {
24171
24564
  active2.child.stdin.write(JSON.stringify({
24172
24565
  type: "control_request",
24173
- request_id: `clox_interrupt_${(0, import_crypto3.randomUUID)()}`,
24566
+ request_id: `clox_interrupt_${(0, import_crypto4.randomUUID)()}`,
24174
24567
  request: { subtype: "interrupt" }
24175
24568
  }) + "\n");
24176
24569
  } catch {
@@ -24216,7 +24609,7 @@ var init_claude_session = __esm({
24216
24609
  }
24217
24610
  }
24218
24611
  async runSession(turn, callbacks, cli, existing) {
24219
- const sessionId = existing || (0, import_crypto3.randomUUID)();
24612
+ const sessionId = existing || (0, import_crypto4.randomUUID)();
24220
24613
  const proxyPath = import_path11.default.join(__dirname, "mcp-proxy.js");
24221
24614
  const mcpConfig = JSON.stringify({
24222
24615
  mcpServers: {
@@ -25366,12 +25759,12 @@ var init_codex_session = __esm({
25366
25759
  });
25367
25760
 
25368
25761
  // ../desktop_ui/remote-host/muse-session.ts
25369
- var import_child_process8, import_crypto4, import_fs14, import_os9, import_path13, TURN_TIMEOUT_MS3, CLOX_TOOL_PREFIX, MUSE_NOT_SIGNED_IN, objectValue3, stringValue, SETTINGS_SCHEMA_VERSION, MuseSessionRunner, linkQuietly, isSymlink, museFailureMessage;
25762
+ var import_child_process8, import_crypto5, import_fs14, import_os9, import_path13, TURN_TIMEOUT_MS3, CLOX_TOOL_PREFIX, MUSE_NOT_SIGNED_IN, objectValue3, stringValue, SETTINGS_SCHEMA_VERSION, MuseSessionRunner, linkQuietly, isSymlink, museFailureMessage;
25370
25763
  var init_muse_session = __esm({
25371
25764
  "../desktop_ui/remote-host/muse-session.ts"() {
25372
25765
  "use strict";
25373
25766
  import_child_process8 = require("child_process");
25374
- import_crypto4 = require("crypto");
25767
+ import_crypto5 = require("crypto");
25375
25768
  import_fs14 = __toESM(require("fs"));
25376
25769
  import_os9 = __toESM(require("os"));
25377
25770
  import_path13 = __toESM(require("path"));
@@ -25435,7 +25828,7 @@ var init_muse_session = __esm({
25435
25828
  }
25436
25829
  }
25437
25830
  async runSession(turn, callbacks, cli, existing) {
25438
- const sessionId = existing || (0, import_crypto4.randomUUID)();
25831
+ const sessionId = existing || (0, import_crypto5.randomUUID)();
25439
25832
  const prompt = existing ? promptForTurn(turn) : [
25440
25833
  "<clox_instructions>",
25441
25834
  systemPromptForAgentVersion(turn.agentVersion),
@@ -25715,12 +26108,12 @@ var init_muse_session = __esm({
25715
26108
  });
25716
26109
 
25717
26110
  // ../desktop_ui/remote-host/grok-session.ts
25718
- var import_child_process9, import_crypto5, import_fs15, import_path14, TURN_TIMEOUT_MS4, CLOX_TOOL_PREFIX2, GROK_NOT_SIGNED_IN, objectValue4, GrokSessionRunner, withCloxToolServer, terminate, linkQuietly2, isSymlink2, grokFailureMessage;
26111
+ var import_child_process9, import_crypto6, import_fs15, import_path14, TURN_TIMEOUT_MS4, CLOX_TOOL_PREFIX2, GROK_NOT_SIGNED_IN, objectValue4, GrokSessionRunner, withCloxToolServer, terminate, linkQuietly2, isSymlink2, grokFailureMessage;
25719
26112
  var init_grok_session = __esm({
25720
26113
  "../desktop_ui/remote-host/grok-session.ts"() {
25721
26114
  "use strict";
25722
26115
  import_child_process9 = require("child_process");
25723
- import_crypto5 = require("crypto");
26116
+ import_crypto6 = require("crypto");
25724
26117
  import_fs15 = __toESM(require("fs"));
25725
26118
  import_path14 = __toESM(require("path"));
25726
26119
  init_capabilities();
@@ -25773,7 +26166,7 @@ var init_grok_session = __esm({
25773
26166
  }
25774
26167
  }
25775
26168
  async runSession(turn, callbacks, cli, existing) {
25776
- const sessionId = existing || (0, import_crypto5.randomUUID)();
26169
+ const sessionId = existing || (0, import_crypto6.randomUUID)();
25777
26170
  const promptDir = import_fs15.default.mkdtempSync(
25778
26171
  import_path14.default.join(this.config.grokHome, "prompt-")
25779
26172
  );
@@ -26025,12 +26418,12 @@ var init_grok_session = __esm({
26025
26418
  });
26026
26419
 
26027
26420
  // ../desktop_ui/remote-host/gemini-session.ts
26028
- var import_child_process10, import_crypto6, import_fs16, import_os10, import_path15, TURN_TIMEOUT_MS5, CLOX_SERVER, GEMINI_NOT_READY, objectValue5, stringValue2, GeminiSessionRunner, registerAntigravityBridge, writeIfChanged, terminate2, geminiFailureMessage;
26421
+ var import_child_process10, import_crypto7, import_fs16, import_os10, import_path15, TURN_TIMEOUT_MS5, CLOX_SERVER, GEMINI_NOT_READY, objectValue5, stringValue2, GeminiSessionRunner, registerAntigravityBridge, writeIfChanged, terminate2, geminiFailureMessage;
26029
26422
  var init_gemini_session = __esm({
26030
26423
  "../desktop_ui/remote-host/gemini-session.ts"() {
26031
26424
  "use strict";
26032
26425
  import_child_process10 = require("child_process");
26033
- import_crypto6 = require("crypto");
26426
+ import_crypto7 = require("crypto");
26034
26427
  import_fs16 = __toESM(require("fs"));
26035
26428
  import_os10 = __toESM(require("os"));
26036
26429
  import_path15 = __toESM(require("path"));
@@ -26118,7 +26511,7 @@ var init_gemini_session = __esm({
26118
26511
  env = {};
26119
26512
  } else {
26120
26513
  this.prepareGeminiCliHome();
26121
- if (!sessionId) sessionId = (0, import_crypto6.randomUUID)();
26514
+ if (!sessionId) sessionId = (0, import_crypto7.randomUUID)();
26122
26515
  args = [
26123
26516
  "-p",
26124
26517
  prompt,
@@ -26394,11 +26787,11 @@ var init_gemini_session = __esm({
26394
26787
  });
26395
26788
 
26396
26789
  // ../desktop_ui/remote-host/local-tool-server.ts
26397
- var import_crypto7, import_http, readBody, writeJson, startLocalToolServer;
26790
+ var import_crypto8, import_http, readBody, writeJson, startLocalToolServer;
26398
26791
  var init_local_tool_server = __esm({
26399
26792
  "../desktop_ui/remote-host/local-tool-server.ts"() {
26400
26793
  "use strict";
26401
- import_crypto7 = require("crypto");
26794
+ import_crypto8 = require("crypto");
26402
26795
  import_http = __toESM(require("http"));
26403
26796
  readBody = (request2) => new Promise((resolve, reject) => {
26404
26797
  let body = "";
@@ -26421,7 +26814,7 @@ var init_local_tool_server = __esm({
26421
26814
  response.end(JSON.stringify(body));
26422
26815
  };
26423
26816
  startLocalToolServer = async (router) => {
26424
- const token = (0, import_crypto7.randomBytes)(32).toString("base64url");
26817
+ const token = (0, import_crypto8.randomBytes)(32).toString("base64url");
26425
26818
  const server = import_http.default.createServer(async (request2, response) => {
26426
26819
  if (request2.headers.authorization !== `Bearer ${token}`) {
26427
26820
  writeJson(response, 401, { error: "unauthorized" });
@@ -32849,12 +33242,12 @@ var init_computer_runner = __esm({
32849
33242
  * Never send messages, emails, or social-media posts unless explicitly asked. If the user asks you to "draft" something, leave it unsent.
32850
33243
  </SAFETY>`;
32851
33244
  displayInfoFor = (display2) => {
32852
- const { width, height } = display2.size;
32853
- const scale = width > MAX_WIDTH ? MAX_WIDTH / width : 1;
32854
- const imageWidth = Math.round(width * scale);
33245
+ const { width: width2, height } = display2.size;
33246
+ const scale = width2 > MAX_WIDTH ? MAX_WIDTH / width2 : 1;
33247
+ const imageWidth = Math.round(width2 * scale);
32855
33248
  const imageHeight = Math.round(height * scale);
32856
33249
  return {
32857
- logicalWidth: width,
33250
+ logicalWidth: width2,
32858
33251
  logicalHeight: height,
32859
33252
  imageWidth,
32860
33253
  imageHeight,
@@ -33592,11 +33985,11 @@ var init_sign_in_window = __esm({
33592
33985
  });
33593
33986
  win.setBrowserView(browser2);
33594
33987
  const layout = () => {
33595
- const [width, height] = win.getContentSize();
33988
+ const [width2, height] = win.getContentSize();
33596
33989
  browser2.setBounds({
33597
33990
  x: 0,
33598
33991
  y: HEADER_HEIGHT,
33599
- width,
33992
+ width: width2,
33600
33993
  height: Math.max(1, height - HEADER_HEIGHT)
33601
33994
  });
33602
33995
  browser2.setAutoResize({ width: true, height: true });
@@ -34222,11 +34615,11 @@ var init_store = __esm({
34222
34615
  });
34223
34616
 
34224
34617
  // ../desktop_ui/openclaw/gateway-client.ts
34225
- var import_crypto8, GATEWAY_OPERATOR_SCOPES, CONNECT_TIMEOUT_MS, normalizeMeta, buildDeviceAuthPayloadV3, signDevicePayload, GatewayClient;
34618
+ var import_crypto9, GATEWAY_OPERATOR_SCOPES, CONNECT_TIMEOUT_MS, normalizeMeta, buildDeviceAuthPayloadV3, signDevicePayload, GatewayClient;
34226
34619
  var init_gateway_client = __esm({
34227
34620
  "../desktop_ui/openclaw/gateway-client.ts"() {
34228
34621
  "use strict";
34229
- import_crypto8 = __toESM(require("crypto"));
34622
+ import_crypto9 = __toESM(require("crypto"));
34230
34623
  init_wrapper();
34231
34624
  GATEWAY_OPERATOR_SCOPES = [
34232
34625
  "operator.admin",
@@ -34252,8 +34645,8 @@ var init_gateway_client = __esm({
34252
34645
  normalizeMeta(args.deviceFamily)
34253
34646
  ].join("|");
34254
34647
  signDevicePayload = (privateKeyPem, payload) => {
34255
- const key = import_crypto8.default.createPrivateKey(privateKeyPem);
34256
- const sig = import_crypto8.default.sign(
34648
+ const key = import_crypto9.default.createPrivateKey(privateKeyPem);
34649
+ const sig = import_crypto9.default.sign(
34257
34650
  null,
34258
34651
  Buffer.from(payload, "utf-8"),
34259
34652
  key
@@ -34277,7 +34670,7 @@ var init_gateway_client = __esm({
34277
34670
  new Error("gateway socket is closed")
34278
34671
  );
34279
34672
  }
34280
- const id = import_crypto8.default.randomUUID();
34673
+ const id = import_crypto9.default.randomUUID();
34281
34674
  return new Promise((resolve, reject) => {
34282
34675
  const timer = setTimeout(() => {
34283
34676
  this.pending.delete(id);
@@ -34864,13 +35257,13 @@ var init_persona = __esm({
34864
35257
  });
34865
35258
 
34866
35259
  // ../desktop_ui/openclaw/manager.ts
34867
- var import_electron4, import_child_process13, import_crypto9, import_fs19, import_net, import_os11, import_path33, log8, logErr4, OPENCLAW_AGENT_ID, DEFAULT_PORT, PORT_SCAN_RANGE, MAX_RESTARTS, STABLE_UPTIME_MS, OPERATOR_SCOPES, options, child, status2, lastError, chosenPort, restartCount, restartTimer, spawnedAtMs, quitting, sessionCtx, cachedVersion, identityCache, basePort, cloxCallbackBaseUrl, stateDir, openclawHome, configPath2, pairedPath, workspaceDir, binDir, cloxCliJsPath, waLoginDriverPath, identityPath, sessionFilePath, bootstrapMarkerPath, BOOTSTRAP_TEMPLATE_REV, bootstrapRev, mkdirp, writeFileAtomic2, base64url, getLanIPv4, isPortFree, pickFreePort, reapStaleOwnGateways, resolveOpenclawPkgJson, resolveOpenclawCli, getOpenclawVersion, ensureGatewayToken, rawPublicKeyFromSpkiDer, ensureDeviceIdentity, localCliCommand, codexBackend, claudeBackend, localModelConfig, buildGatewayConfig, writeGatewayConfig, writePairedJson, desktopControl, writeSessionFile, WHATSAPP_REPLY_MARKER, browserUserDataDir, AGENTS_MD, buildCloxWrapper, CLOX_CLI_JS, WA_LOGIN_DRIVER_MJS, readBootstrapMarker, bootstrapWorkspace, clearRestartTimer, scheduleRestart, spawnGateway, ensureOpenClawGatewayStarted, readAgentSessionStatus, isGatewayRunning, isOpenClawEnabled, getGatewayInfo, getRunnerConnection, whatsAppAuthDir, whatsAppCredsPath, WA_LINK_TIMEOUT_MS, readWhatsAppSelfE164, whatsAppChannelBlock, PAIRING_TTL_MS;
35260
+ var import_electron4, import_child_process13, import_crypto10, import_fs19, import_net, import_os11, import_path33, log8, logErr4, OPENCLAW_AGENT_ID, DEFAULT_PORT, PORT_SCAN_RANGE, MAX_RESTARTS, STABLE_UPTIME_MS, OPERATOR_SCOPES, options, child, status2, lastError, chosenPort, restartCount, restartTimer, spawnedAtMs, quitting, sessionCtx, cachedVersion, identityCache, basePort, cloxCallbackBaseUrl, stateDir, openclawHome, configPath2, pairedPath, workspaceDir, binDir, cloxCliJsPath, waLoginDriverPath, identityPath, sessionFilePath, bootstrapMarkerPath, BOOTSTRAP_TEMPLATE_REV, bootstrapRev, mkdirp, writeFileAtomic2, base64url, getLanIPv4, isPortFree, pickFreePort, reapStaleOwnGateways, resolveOpenclawPkgJson, resolveOpenclawCli, getOpenclawVersion, ensureGatewayToken, rawPublicKeyFromSpkiDer, ensureDeviceIdentity, localCliCommand, codexBackend, claudeBackend, localModelConfig, buildGatewayConfig, writeGatewayConfig, writePairedJson, desktopControl, writeSessionFile, WHATSAPP_REPLY_MARKER, browserUserDataDir, AGENTS_MD, buildCloxWrapper, CLOX_CLI_JS, WA_LOGIN_DRIVER_MJS, readBootstrapMarker, bootstrapWorkspace, clearRestartTimer, scheduleRestart, spawnGateway, ensureOpenClawGatewayStarted, readAgentSessionStatus, isGatewayRunning, isOpenClawEnabled, getGatewayInfo, getRunnerConnection, whatsAppAuthDir, whatsAppCredsPath, WA_LINK_TIMEOUT_MS, readWhatsAppSelfE164, whatsAppChannelBlock, PAIRING_TTL_MS;
34868
35261
  var init_manager = __esm({
34869
35262
  "../desktop_ui/openclaw/manager.ts"() {
34870
35263
  "use strict";
34871
35264
  import_electron4 = require("electron");
34872
35265
  import_child_process13 = require("child_process");
34873
- import_crypto9 = __toESM(require("crypto"));
35266
+ import_crypto10 = __toESM(require("crypto"));
34874
35267
  import_fs19 = __toESM(require("fs"));
34875
35268
  import_net = __toESM(require("net"));
34876
35269
  import_os11 = __toESM(require("os"));
@@ -35074,7 +35467,7 @@ var init_manager = __esm({
35074
35467
  if (!options) return "";
35075
35468
  let token = (options.getGatewayToken() || "").trim();
35076
35469
  if (!token) {
35077
- token = base64url(import_crypto9.default.randomBytes(32));
35470
+ token = base64url(import_crypto10.default.randomBytes(32));
35078
35471
  options.setGatewayToken(token);
35079
35472
  log8("generated per-install gateway token");
35080
35473
  }
@@ -35100,7 +35493,7 @@ var init_manager = __esm({
35100
35493
  }
35101
35494
  } catch {
35102
35495
  }
35103
- const pair = import_crypto9.default.generateKeyPairSync("ed25519");
35496
+ const pair = import_crypto10.default.generateKeyPairSync("ed25519");
35104
35497
  const privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }).toString();
35105
35498
  const spkiDer = pair.publicKey.export({
35106
35499
  type: "spki",
@@ -35109,7 +35502,7 @@ var init_manager = __esm({
35109
35502
  const rawPub = rawPublicKeyFromSpkiDer(
35110
35503
  Buffer.from(spkiDer)
35111
35504
  );
35112
- const deviceId = import_crypto9.default.createHash("sha256").update(rawPub).digest("hex");
35505
+ const deviceId = import_crypto10.default.createHash("sha256").update(rawPub).digest("hex");
35113
35506
  const identity2 = {
35114
35507
  deviceId,
35115
35508
  publicKeyRawB64: base64url(rawPub),
@@ -36848,13 +37241,13 @@ var init_panel = __esm({
36848
37241
  throw new Error("Another sign-in is already in progress");
36849
37242
  }
36850
37243
  const display2 = import_electron5.screen.getDisplayNearestPoint(import_electron5.screen.getCursorScreenPoint());
36851
- const width = 440;
37244
+ const width2 = 440;
36852
37245
  const height = 196;
36853
37246
  const { x, y, width: areaW } = display2.workArea;
36854
37247
  const win = new import_electron5.BrowserWindow({
36855
- width,
37248
+ width: width2,
36856
37249
  height,
36857
- x: Math.round(x + areaW - width - 24),
37250
+ x: Math.round(x + areaW - width2 - 24),
36858
37251
  y: y + 24,
36859
37252
  resizable: false,
36860
37253
  minimizable: false,
@@ -37177,12 +37570,12 @@ var init_pending_input = __esm({
37177
37570
  });
37178
37571
 
37179
37572
  // ../desktop_ui/remote-host/tools.ts
37180
- var import_child_process14, import_crypto10, import_os12, import_electron6, deviceKindForName, shellActivitySummary, deviceActionSummary, localDefinitions, LINUX_APPS, openLinuxApp, execFileAsync, SCREENSHOT_FOLDER, RemoteToolRouter;
37573
+ var import_child_process14, import_crypto11, import_os12, import_electron6, deviceKindForName, shellActivitySummary, deviceActionSummary, localDefinitions, LINUX_APPS, openLinuxApp, execFileAsync, SCREENSHOT_FOLDER, RemoteToolRouter;
37181
37574
  var init_tools = __esm({
37182
37575
  "../desktop_ui/remote-host/tools.ts"() {
37183
37576
  "use strict";
37184
37577
  import_child_process14 = require("child_process");
37185
- import_crypto10 = require("crypto");
37578
+ import_crypto11 = require("crypto");
37186
37579
  import_os12 = __toESM(require("os"));
37187
37580
  import_electron6 = require("electron");
37188
37581
  init_computer_runner();
@@ -37383,7 +37776,7 @@ var init_tools = __esm({
37383
37776
  */
37384
37777
  async shareScreenshot(base642) {
37385
37778
  try {
37386
- const objectPath = `${SCREENSHOT_FOLDER}/${(0, import_crypto10.randomUUID)()}/${(0, import_crypto10.randomUUID)()}.jpg`;
37779
+ const objectPath = `${SCREENSHOT_FOLDER}/${(0, import_crypto11.randomUUID)()}/${(0, import_crypto11.randomUUID)()}.jpg`;
37387
37780
  const response = await fetch(`${this.baseUrl}/query`, {
37388
37781
  method: "POST",
37389
37782
  headers: {
@@ -37480,7 +37873,7 @@ var init_tools = __esm({
37480
37873
  }
37481
37874
  getDefinitionsFingerprint(agentVersion) {
37482
37875
  const serialized = JSON.stringify(this.getDefinitions(agentVersion));
37483
- return (0, import_crypto10.createHash)("sha256").update(serialized).digest("hex");
37876
+ return (0, import_crypto11.createHash)("sha256").update(serialized).digest("hex");
37484
37877
  }
37485
37878
  async call(name5, args, context) {
37486
37879
  if (this.serverToolNames.has(name5)) {
@@ -37724,12 +38117,116 @@ var init_provider_routing = __esm({
37724
38117
  }
37725
38118
  });
37726
38119
 
38120
+ // ../desktop_ui/remote-host/screen-share.ts
38121
+ var WATCH_MS, FRAME_MS, ScreenShare;
38122
+ var init_screen_share = __esm({
38123
+ "../desktop_ui/remote-host/screen-share.ts"() {
38124
+ "use strict";
38125
+ init_computer_runner();
38126
+ WATCH_MS = 12e3;
38127
+ FRAME_MS = 500;
38128
+ ScreenShare = class {
38129
+ constructor(baseUrl, sessionToken, deviceId) {
38130
+ this.baseUrl = baseUrl;
38131
+ this.sessionToken = sessionToken;
38132
+ this.deviceId = deviceId;
38133
+ this.watchUntil = 0;
38134
+ this.running = false;
38135
+ /** Inputs run one after another, in the order they were made: typing
38136
+ * must finish before the Return that follows it. */
38137
+ this.inputs = Promise.resolve();
38138
+ }
38139
+ /** Someone is looking: keep pictures coming for a while. */
38140
+ watch() {
38141
+ this.watchUntil = Date.now() + WATCH_MS;
38142
+ if (!this.running) void this.loop();
38143
+ }
38144
+ async loop() {
38145
+ this.running = true;
38146
+ try {
38147
+ while (Date.now() < this.watchUntil) {
38148
+ const started = Date.now();
38149
+ await this.sendFrame().catch(() => {
38150
+ });
38151
+ const wait = FRAME_MS - (Date.now() - started);
38152
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
38153
+ }
38154
+ } finally {
38155
+ this.running = false;
38156
+ }
38157
+ }
38158
+ async sendFrame() {
38159
+ const jpeg = await captureScreenshot(getDisplayInfo());
38160
+ if (!jpeg) return;
38161
+ await fetch(
38162
+ `${this.baseUrl}/api/device/screen/frame?deviceId=${encodeURIComponent(this.deviceId)}`,
38163
+ {
38164
+ method: "POST",
38165
+ headers: {
38166
+ "Content-Type": "image/jpeg",
38167
+ Authorization: `Bearer ${this.sessionToken()}`
38168
+ },
38169
+ body: Buffer.from(jpeg, "base64")
38170
+ }
38171
+ );
38172
+ }
38173
+ /** Does what the person did on the picture, here, after anything
38174
+ * they did before it. */
38175
+ input(raw) {
38176
+ const next = this.inputs.then(() => this.apply(raw)).catch(() => {
38177
+ });
38178
+ this.inputs = next;
38179
+ return next;
38180
+ }
38181
+ async apply(raw) {
38182
+ let input;
38183
+ try {
38184
+ input = JSON.parse(raw);
38185
+ } catch {
38186
+ return;
38187
+ }
38188
+ const display2 = getDisplayInfo();
38189
+ const at = () => [
38190
+ Math.round((input.x ?? 0) * display2.imageWidth),
38191
+ Math.round((input.y ?? 0) * display2.imageHeight)
38192
+ ];
38193
+ switch (input.kind) {
38194
+ case "tap":
38195
+ await executeComputerAction({ action: "left_click", coordinate: at() }, display2);
38196
+ break;
38197
+ case "type":
38198
+ if (input.text) {
38199
+ await executeComputerAction({ action: "type", text: input.text }, display2);
38200
+ }
38201
+ break;
38202
+ case "key":
38203
+ if (input.key) {
38204
+ await executeComputerAction({ action: "key", text: input.key }, display2);
38205
+ }
38206
+ break;
38207
+ case "scroll":
38208
+ await executeComputerAction({
38209
+ action: "scroll",
38210
+ coordinate: at(),
38211
+ scroll_direction: input.direction === "up" ? "up" : "down",
38212
+ scroll_amount: 5
38213
+ }, display2);
38214
+ break;
38215
+ }
38216
+ this.watch();
38217
+ await this.sendFrame().catch(() => {
38218
+ });
38219
+ }
38220
+ };
38221
+ }
38222
+ });
38223
+
37727
38224
  // ../desktop_ui/remote-host/client.ts
37728
38225
  var client_exports = {};
37729
38226
  __export(client_exports, {
37730
38227
  RemoteHostClient: () => RemoteHostClient
37731
38228
  });
37732
- var log10, logErr5, sleep5, INITIAL_QUIET_PROGRESS_MS, REPEATED_QUIET_PROGRESS_MS, TOOL_MANIFEST_MAX_AGE_MS, EXECUTOR_KEYS_REFRESH_MS, OPENROUTER_ANTHROPIC_BASE_URL, OPENROUTER_NOT_READY, quietProgressText, executorLabel, friendlyToolProgress, RemoteHostClient;
38229
+ var import_electron7, log10, logErr5, sleep5, INITIAL_QUIET_PROGRESS_MS, REPEATED_QUIET_PROGRESS_MS, TOOL_MANIFEST_MAX_AGE_MS, EXECUTOR_KEYS_REFRESH_MS, OPENROUTER_ANTHROPIC_BASE_URL, OPENROUTER_NOT_READY, quietProgressText, executorLabel, friendlyToolProgress, RemoteHostClient;
37733
38230
  var init_client4 = __esm({
37734
38231
  "../desktop_ui/remote-host/client.ts"() {
37735
38232
  "use strict";
@@ -37748,6 +38245,8 @@ var init_client4 = __esm({
37748
38245
  init_agent_profile();
37749
38246
  init_types2();
37750
38247
  init_provider_routing();
38248
+ init_screen_share();
38249
+ import_electron7 = require("electron");
37751
38250
  log10 = (...args) => console.log("[remote-host]", ...args);
37752
38251
  logErr5 = (...args) => console.error("[remote-host]", ...args);
37753
38252
  sleep5 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -37821,6 +38320,11 @@ var init_client4 = __esm({
37821
38320
  this.outbox = [];
37822
38321
  this.businessSyncedAt = /* @__PURE__ */ new Map();
37823
38322
  this.cancelledTurns = /* @__PURE__ */ new Set();
38323
+ this.screen = new ScreenShare(
38324
+ config2.baseUrl,
38325
+ () => config2.sessionToken,
38326
+ config2.deviceId
38327
+ );
37824
38328
  }
37825
38329
  async start() {
37826
38330
  this.stopped = false;
@@ -38180,6 +38684,22 @@ var init_client4 = __esm({
38180
38684
  }
38181
38685
  async handleControl(control) {
38182
38686
  if (control.deviceId !== this.config.deviceId) return;
38687
+ if (control.action === "watch") {
38688
+ this.screen.watch();
38689
+ return;
38690
+ }
38691
+ if (control.action === "input") {
38692
+ await this.screen.input(control.message ?? "");
38693
+ return;
38694
+ }
38695
+ if (control.action === "open") {
38696
+ const url = control.message ?? "";
38697
+ if (!/^https:\/\/[a-z0-9.-]+$/i.test(url)) return;
38698
+ await import_electron7.shell.openExternal(url);
38699
+ this.screen.watch();
38700
+ log10("opened a website to sign in to");
38701
+ return;
38702
+ }
38183
38703
  if (control.action === "rescan") {
38184
38704
  const executors = await this.executors();
38185
38705
  this.socket?.send(JSON.stringify({ type: "executors", executors }));
@@ -39594,7 +40114,7 @@ function promisifyRequest(request2) {
39594
40114
  request2.removeEventListener("error", error);
39595
40115
  };
39596
40116
  const success = () => {
39597
- resolve(wrap(request2.result));
40117
+ resolve(wrap2(request2.result));
39598
40118
  unlisten();
39599
40119
  };
39600
40120
  const error = () => {
@@ -39644,17 +40164,17 @@ function wrapFunction(func) {
39644
40164
  return function(storeNames, ...args) {
39645
40165
  const tx = func.call(unwrap(this), storeNames, ...args);
39646
40166
  transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
39647
- return wrap(tx);
40167
+ return wrap2(tx);
39648
40168
  };
39649
40169
  }
39650
40170
  if (getCursorAdvanceMethods().includes(func)) {
39651
40171
  return function(...args) {
39652
40172
  func.apply(unwrap(this), args);
39653
- return wrap(cursorRequestMap.get(this));
40173
+ return wrap2(cursorRequestMap.get(this));
39654
40174
  };
39655
40175
  }
39656
40176
  return function(...args) {
39657
- return wrap(func.apply(unwrap(this), args));
40177
+ return wrap2(func.apply(unwrap(this), args));
39658
40178
  };
39659
40179
  }
39660
40180
  function transformCachableValue(value) {
@@ -39666,7 +40186,7 @@ function transformCachableValue(value) {
39666
40186
  return new Proxy(value, idbProxyTraps);
39667
40187
  return value;
39668
40188
  }
39669
- function wrap(value) {
40189
+ function wrap2(value) {
39670
40190
  if (value instanceof IDBRequest)
39671
40191
  return promisifyRequest(value);
39672
40192
  if (transformCache.has(value))
@@ -39699,7 +40219,7 @@ var init_wrap_idb_value = __esm({
39699
40219
  return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]);
39700
40220
  }
39701
40221
  }
39702
- return wrap(target[prop]);
40222
+ return wrap2(target[prop]);
39703
40223
  },
39704
40224
  set(target, prop, value) {
39705
40225
  target[prop] = value;
@@ -39719,10 +40239,10 @@ var init_wrap_idb_value = __esm({
39719
40239
  // ../node_modules/idb/build/index.js
39720
40240
  function openDB(name5, version6, { blocked: blocked2, upgrade, blocking, terminated } = {}) {
39721
40241
  const request2 = indexedDB.open(name5, version6);
39722
- const openPromise = wrap(request2);
40242
+ const openPromise = wrap2(request2);
39723
40243
  if (upgrade) {
39724
40244
  request2.addEventListener("upgradeneeded", (event) => {
39725
- upgrade(wrap(request2.result), event.oldVersion, event.newVersion, wrap(request2.transaction), event);
40245
+ upgrade(wrap2(request2.result), event.oldVersion, event.newVersion, wrap2(request2.transaction), event);
39726
40246
  });
39727
40247
  }
39728
40248
  if (blocked2) {
@@ -64408,7 +64928,7 @@ function makeAuthCredentialsProvider(credentials2) {
64408
64928
  }
64409
64929
  }
64410
64930
  function randomBytes2(nBytes) {
64411
- return (0, import_crypto11.randomBytes)(nBytes);
64931
+ return (0, import_crypto12.randomBytes)(nBytes);
64412
64932
  }
64413
64933
  function primitiveComparator(left, right) {
64414
64934
  if (left < right) {
@@ -68830,7 +69350,7 @@ function createError(reason, methodName, hasConverter, path25, targetDoc) {
68830
69350
  function fieldMaskContains(haystack, needle) {
68831
69351
  return haystack.some((v) => v.isEqual(needle));
68832
69352
  }
68833
- var import_util9, import_crypto11, grpc, protoLoader, User, version4, SDK_VERSION2, logClient2, Code, FirestoreError, Deferred2, OAuthToken, EmptyAuthCredentialsProvider, EmulatorAuthCredentialsProvider, FirebaseAuthCredentialsProvider, FirstPartyToken, FirstPartyAuthCredentialsProvider, AppCheckToken, FirebaseAppCheckTokenProvider, AutoId, MIN_SURROGATE$1, MAX_SURROGATE$1, DOCUMENT_KEY_NAME, BasePath, ResourcePath, identifierRegExp, FieldPath$1, DocumentKey, MIN_SECONDS, MS_TO_NANOS, Timestamp, SnapshotVersion, INITIAL_LARGEST_BATCH_ID, FieldIndex, IndexOffset, PRIMARY_LEASE_LOST_ERROR_MSG, PersistenceTransaction, PersistencePromise, INITIAL_BACKFILL_DELAY_MS, REGULAR_BACKFILL_DELAY_MS, ListenSequence, escapeChar, encodedSeparatorChar, encodedNul, encodedEscape, DbRemoteDocumentStore$1, DbPrimaryClientStore, DbMutationQueueStore, DbMutationBatchStore, DbDocumentMutationStore, DbRemoteDocumentStore, DbRemoteDocumentGlobalStore, DbTargetStore, DbTargetDocumentStore, DbTargetGlobalStore, DbCollectionParentStore, DbClientMetadataStore, DbBundleStore, DbNamedQueryStore, DbIndexConfigurationStore, DbIndexStateStore, DbIndexEntryStore, DbDocumentOverlayStore, DbGlobalsStore, V1_STORES, V3_STORES, V4_STORES, V6_STORES, V8_STORES, V11_STORES, V12_STORES, V13_STORES, V14_STORES, V15_STORES, V17_STORES, SortedMap, SortedMapIterator, LLRBNode, LLRBEmptyNode, SortedSet, SortedSetIterator, FieldMask, ByteString, ISO_TIMESTAMP_REG_EXP, SERVER_TIMESTAMP_SENTINEL, TYPE_KEY$1, PREVIOUS_VALUE_KEY, LOCAL_WRITE_TIME_KEY, DatabaseInfo, DEFAULT_DATABASE_NAME, DatabaseId, BATCHID_UNKNOWN, TYPE_KEY, MAX_VALUE_TYPE, MAX_VALUE, VECTOR_VALUE_SENTINEL, VECTOR_MAP_VECTORS_KEY, MIN_VECTOR_VALUE, ObjectValue, MutableDocument, Bound, OrderBy, Filter, FieldFilter, CompositeFilter, KeyFieldFilter, KeyFieldInFilter, KeyFieldNotInFilter, ArrayContainsFilter, InFilter, NotInFilter, ArrayContainsAnyFilter, TargetImpl, QueryImpl, ObjectMap, EMPTY_MUTABLE_DOCUMENT_MAP, EMPTY_DOCUMENT_MAP, EMPTY_DOCUMENT_VERSION_MAP, EMPTY_DOCUMENT_KEY_SET, EMPTY_TARGET_ID_SET, TransformOperation, ServerTimestampTransform, ArrayUnionTransformOperation, ArrayRemoveTransformOperation, NumericIncrementTransformOperation, MutationResult, Precondition, Mutation, SetMutation, PatchMutation, DeleteMutation, VerifyMutation, MutationBatch, MutationBatchResult, Overlay, ExistenceFilter, RpcCode, Base64DecodeError, testingHooksSpi, MAX_64_BIT_UNSIGNED_INTEGER, BloomFilter, BloomFilterError, RemoteEvent, TargetChange, DocumentWatchChange, ExistenceFilterChange, WatchTargetChange, TargetState, LOG_TAG$g, WatchChangeAggregator, DIRECTIONS, OPERATORS, COMPOSITE_OPERATORS, JsonProtoSerializer, TargetData, LocalSerializer, INDEX_TYPE_NULL, INDEX_TYPE_BOOLEAN, INDEX_TYPE_NAN, INDEX_TYPE_NUMBER, INDEX_TYPE_TIMESTAMP, INDEX_TYPE_STRING, INDEX_TYPE_BLOB, INDEX_TYPE_REFERENCE, INDEX_TYPE_GEOPOINT, INDEX_TYPE_ARRAY, INDEX_TYPE_VECTOR, INDEX_TYPE_MAP, INDEX_TYPE_REFERENCE_SEGMENT, NOT_TRUNCATED, FirestoreIndexValueWriter, MemoryIndexManager, MemoryCollectionParentIndex, EMPTY_VALUE, OFFSET, TargetIdGenerator, GC_DID_NOT_RUN, LRU_COLLECTION_DISABLED, LRU_DEFAULT_CACHE_SIZE_BYTES, LruParams, LOG_TAG$e, LRU_MINIMUM_CACHE_SIZE_BYTES, INITIAL_GC_DELAY_MS, REGULAR_GC_DELAY_MS, RollingSequenceNumberBuffer, LruScheduler, LruGarbageCollectorImpl, RemoteDocumentChangeBuffer, OverlayedDocument, LocalDocumentsView, MemoryBundleCache, MemoryDocumentOverlayCache, MemoryGlobalsCache, ReferenceSet, DocReference, MemoryMutationQueue, MIN_LONG_VALUE, MemoryRemoteDocumentCacheImpl, MemoryRemoteDocumentChangeBuffer, MemoryTargetCache, LOG_TAG$d, MemoryPersistence, MemoryTransaction, MemoryEagerDelegate, MemoryLruDelegate, MAX_CLIENT_AGE_MS, LOG_TAG$b, RESUME_TOKEN_MAX_AGE_MICROS, LocalStoreImpl, QueryContext, DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE, QueryEngine, LocalClientState, MemorySharedClientState, NoopConnectivityMonitor, StreamBridge, lastUniqueDebugId, grpcVersion, LOG_TAG$9, X_GOOG_API_CLIENT_VALUE, GrpcConnection, options2, nested, protos, protos$1, protoLoaderOptions, LOG_TAG$8, DEFAULT_BACKOFF_INITIAL_DELAY_MS, DEFAULT_BACKOFF_FACTOR, DEFAULT_BACKOFF_MAX_DELAY_MS, ExponentialBackoff, LOG_TAG$7, IDLE_TIMEOUT_MS, HEALTHY_TIMEOUT_MS, PersistentStream, PersistentListenStream, PersistentWriteStream, Datastore, DatastoreImpl, LOG_TAG$6, MAX_WATCH_STREAM_FAILURES, ONLINE_STATE_TIMEOUT_MS, OnlineStateTracker, LOG_TAG$5, MAX_PENDING_WRITES, RemoteStoreImpl, LOG_TAG$4, DelayedOperation, DocumentSet, DocumentChangeSet, ViewSnapshot, QueryListenersInfo, EventManagerImpl, ListenerDataSource, QueryListener, LocalViewChanges, AddedLimboDocument, RemovedLimboDocument, View, LOG_TAG$3, QueryView, LimboResolution, SyncEngineImpl, MemoryOfflineComponentProvider, LruGcMemoryOfflineComponentProvider, OnlineComponentProvider, AsyncObserver, LOG_TAG$2, MAX_CONCURRENT_LIMBO_RESOLUTIONS, DOM_EXCEPTION_INVALID_STATE, DOM_EXCEPTION_ABORTED, DOM_EXCEPTION_QUOTA_EXCEEDED, FirestoreClient, LOG_TAG$1, datastoreInstances, DEFAULT_HOST, DEFAULT_SSL, MIN_LONG_POLLING_TIMEOUT_SECONDS, MAX_LONG_POLLING_TIMEOUT_SECONDS, DEFAULT_AUTO_DETECT_LONG_POLLING, FirestoreSettingsImpl, Firestore$1, Query, DocumentReference, CollectionReference, LOG_TAG, AsyncQueueImpl, Firestore, Bytes, FieldPath, FieldValue, GeoPoint, VectorValue, RESERVED_FIELD_REGEX, ParsedUpdateData, ParseContextImpl, UserDataReader, DeleteFieldValueImpl, FIELD_PATH_RESERVED, AbstractUserDataWriter, ExpUserDataWriter;
69353
+ var import_util9, import_crypto12, grpc, protoLoader, User, version4, SDK_VERSION2, logClient2, Code, FirestoreError, Deferred2, OAuthToken, EmptyAuthCredentialsProvider, EmulatorAuthCredentialsProvider, FirebaseAuthCredentialsProvider, FirstPartyToken, FirstPartyAuthCredentialsProvider, AppCheckToken, FirebaseAppCheckTokenProvider, AutoId, MIN_SURROGATE$1, MAX_SURROGATE$1, DOCUMENT_KEY_NAME, BasePath, ResourcePath, identifierRegExp, FieldPath$1, DocumentKey, MIN_SECONDS, MS_TO_NANOS, Timestamp, SnapshotVersion, INITIAL_LARGEST_BATCH_ID, FieldIndex, IndexOffset, PRIMARY_LEASE_LOST_ERROR_MSG, PersistenceTransaction, PersistencePromise, INITIAL_BACKFILL_DELAY_MS, REGULAR_BACKFILL_DELAY_MS, ListenSequence, escapeChar, encodedSeparatorChar, encodedNul, encodedEscape, DbRemoteDocumentStore$1, DbPrimaryClientStore, DbMutationQueueStore, DbMutationBatchStore, DbDocumentMutationStore, DbRemoteDocumentStore, DbRemoteDocumentGlobalStore, DbTargetStore, DbTargetDocumentStore, DbTargetGlobalStore, DbCollectionParentStore, DbClientMetadataStore, DbBundleStore, DbNamedQueryStore, DbIndexConfigurationStore, DbIndexStateStore, DbIndexEntryStore, DbDocumentOverlayStore, DbGlobalsStore, V1_STORES, V3_STORES, V4_STORES, V6_STORES, V8_STORES, V11_STORES, V12_STORES, V13_STORES, V14_STORES, V15_STORES, V17_STORES, SortedMap, SortedMapIterator, LLRBNode, LLRBEmptyNode, SortedSet, SortedSetIterator, FieldMask, ByteString, ISO_TIMESTAMP_REG_EXP, SERVER_TIMESTAMP_SENTINEL, TYPE_KEY$1, PREVIOUS_VALUE_KEY, LOCAL_WRITE_TIME_KEY, DatabaseInfo, DEFAULT_DATABASE_NAME, DatabaseId, BATCHID_UNKNOWN, TYPE_KEY, MAX_VALUE_TYPE, MAX_VALUE, VECTOR_VALUE_SENTINEL, VECTOR_MAP_VECTORS_KEY, MIN_VECTOR_VALUE, ObjectValue, MutableDocument, Bound, OrderBy, Filter, FieldFilter, CompositeFilter, KeyFieldFilter, KeyFieldInFilter, KeyFieldNotInFilter, ArrayContainsFilter, InFilter, NotInFilter, ArrayContainsAnyFilter, TargetImpl, QueryImpl, ObjectMap, EMPTY_MUTABLE_DOCUMENT_MAP, EMPTY_DOCUMENT_MAP, EMPTY_DOCUMENT_VERSION_MAP, EMPTY_DOCUMENT_KEY_SET, EMPTY_TARGET_ID_SET, TransformOperation, ServerTimestampTransform, ArrayUnionTransformOperation, ArrayRemoveTransformOperation, NumericIncrementTransformOperation, MutationResult, Precondition, Mutation, SetMutation, PatchMutation, DeleteMutation, VerifyMutation, MutationBatch, MutationBatchResult, Overlay, ExistenceFilter, RpcCode, Base64DecodeError, testingHooksSpi, MAX_64_BIT_UNSIGNED_INTEGER, BloomFilter, BloomFilterError, RemoteEvent, TargetChange, DocumentWatchChange, ExistenceFilterChange, WatchTargetChange, TargetState, LOG_TAG$g, WatchChangeAggregator, DIRECTIONS, OPERATORS, COMPOSITE_OPERATORS, JsonProtoSerializer, TargetData, LocalSerializer, INDEX_TYPE_NULL, INDEX_TYPE_BOOLEAN, INDEX_TYPE_NAN, INDEX_TYPE_NUMBER, INDEX_TYPE_TIMESTAMP, INDEX_TYPE_STRING, INDEX_TYPE_BLOB, INDEX_TYPE_REFERENCE, INDEX_TYPE_GEOPOINT, INDEX_TYPE_ARRAY, INDEX_TYPE_VECTOR, INDEX_TYPE_MAP, INDEX_TYPE_REFERENCE_SEGMENT, NOT_TRUNCATED, FirestoreIndexValueWriter, MemoryIndexManager, MemoryCollectionParentIndex, EMPTY_VALUE, OFFSET, TargetIdGenerator, GC_DID_NOT_RUN, LRU_COLLECTION_DISABLED, LRU_DEFAULT_CACHE_SIZE_BYTES, LruParams, LOG_TAG$e, LRU_MINIMUM_CACHE_SIZE_BYTES, INITIAL_GC_DELAY_MS, REGULAR_GC_DELAY_MS, RollingSequenceNumberBuffer, LruScheduler, LruGarbageCollectorImpl, RemoteDocumentChangeBuffer, OverlayedDocument, LocalDocumentsView, MemoryBundleCache, MemoryDocumentOverlayCache, MemoryGlobalsCache, ReferenceSet, DocReference, MemoryMutationQueue, MIN_LONG_VALUE, MemoryRemoteDocumentCacheImpl, MemoryRemoteDocumentChangeBuffer, MemoryTargetCache, LOG_TAG$d, MemoryPersistence, MemoryTransaction, MemoryEagerDelegate, MemoryLruDelegate, MAX_CLIENT_AGE_MS, LOG_TAG$b, RESUME_TOKEN_MAX_AGE_MICROS, LocalStoreImpl, QueryContext, DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE, QueryEngine, LocalClientState, MemorySharedClientState, NoopConnectivityMonitor, StreamBridge, lastUniqueDebugId, grpcVersion, LOG_TAG$9, X_GOOG_API_CLIENT_VALUE, GrpcConnection, options2, nested, protos, protos$1, protoLoaderOptions, LOG_TAG$8, DEFAULT_BACKOFF_INITIAL_DELAY_MS, DEFAULT_BACKOFF_FACTOR, DEFAULT_BACKOFF_MAX_DELAY_MS, ExponentialBackoff, LOG_TAG$7, IDLE_TIMEOUT_MS, HEALTHY_TIMEOUT_MS, PersistentStream, PersistentListenStream, PersistentWriteStream, Datastore, DatastoreImpl, LOG_TAG$6, MAX_WATCH_STREAM_FAILURES, ONLINE_STATE_TIMEOUT_MS, OnlineStateTracker, LOG_TAG$5, MAX_PENDING_WRITES, RemoteStoreImpl, LOG_TAG$4, DelayedOperation, DocumentSet, DocumentChangeSet, ViewSnapshot, QueryListenersInfo, EventManagerImpl, ListenerDataSource, QueryListener, LocalViewChanges, AddedLimboDocument, RemovedLimboDocument, View, LOG_TAG$3, QueryView, LimboResolution, SyncEngineImpl, MemoryOfflineComponentProvider, LruGcMemoryOfflineComponentProvider, OnlineComponentProvider, AsyncObserver, LOG_TAG$2, MAX_CONCURRENT_LIMBO_RESOLUTIONS, DOM_EXCEPTION_INVALID_STATE, DOM_EXCEPTION_ABORTED, DOM_EXCEPTION_QUOTA_EXCEEDED, FirestoreClient, LOG_TAG$1, datastoreInstances, DEFAULT_HOST, DEFAULT_SSL, MIN_LONG_POLLING_TIMEOUT_SECONDS, MAX_LONG_POLLING_TIMEOUT_SECONDS, DEFAULT_AUTO_DETECT_LONG_POLLING, FirestoreSettingsImpl, Firestore$1, Query, DocumentReference, CollectionReference, LOG_TAG, AsyncQueueImpl, Firestore, Bytes, FieldPath, FieldValue, GeoPoint, VectorValue, RESERVED_FIELD_REGEX, ParsedUpdateData, ParseContextImpl, UserDataReader, DeleteFieldValueImpl, FIELD_PATH_RESERVED, AbstractUserDataWriter, ExpUserDataWriter;
68834
69354
  var init_common_b12d6a5a_node = __esm({
68835
69355
  "../node_modules/@firebase/firestore/dist/common-b12d6a5a.node.mjs"() {
68836
69356
  init_index_esm3();
@@ -68838,7 +69358,7 @@ var init_common_b12d6a5a_node = __esm({
68838
69358
  init_bloom_blob_es2018();
68839
69359
  init_index_esm2();
68840
69360
  import_util9 = require("util");
68841
- import_crypto11 = require("crypto");
69361
+ import_crypto12 = require("crypto");
68842
69362
  grpc = __toESM(require_src3(), 1);
68843
69363
  protoLoader = __toESM(require_src2(), 1);
68844
69364
  User = class {
@@ -70219,17 +70739,17 @@ var init_common_b12d6a5a_node = __esm({
70219
70739
  }
70220
70740
  };
70221
70741
  LLRBNode = class _LLRBNode {
70222
- constructor(key, value, color, left, right) {
70742
+ constructor(key, value, color2, left, right) {
70223
70743
  this.key = key;
70224
70744
  this.value = value;
70225
- this.color = color != null ? color : _LLRBNode.RED;
70745
+ this.color = color2 != null ? color2 : _LLRBNode.RED;
70226
70746
  this.left = left != null ? left : _LLRBNode.EMPTY;
70227
70747
  this.right = right != null ? right : _LLRBNode.EMPTY;
70228
70748
  this.size = this.left.size + 1 + this.right.size;
70229
70749
  }
70230
70750
  // Returns a copy of the current node, optionally replacing pieces of it.
70231
- copy(key, value, color, left, right) {
70232
- return new _LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
70751
+ copy(key, value, color2, left, right) {
70752
+ return new _LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color2 != null ? color2 : this.color, left != null ? left : this.left, right != null ? right : this.right);
70233
70753
  }
70234
70754
  isEmpty() {
70235
70755
  return false;
@@ -70422,7 +70942,7 @@ var init_common_b12d6a5a_node = __esm({
70422
70942
  throw fail(36894);
70423
70943
  }
70424
70944
  // Returns a copy of the current node.
70425
- copy(key, value, color, left, right) {
70945
+ copy(key, value, color2, left, right) {
70426
70946
  return this;
70427
70947
  }
70428
70948
  // Returns a copy of the tree, with the specified key/value added.
@@ -82709,8 +83229,8 @@ var init_openclaw_runner = __esm({
82709
83229
  };
82710
83230
  lastAssistantTextFromHistory = (payload) => {
82711
83231
  if (!payload || typeof payload !== "object") return "";
82712
- const wrap2 = payload;
82713
- const messages = Array.isArray(wrap2.messages) ? wrap2.messages : [];
83232
+ const wrap3 = payload;
83233
+ const messages = Array.isArray(wrap3.messages) ? wrap3.messages : [];
82714
83234
  for (let i = messages.length - 1; i >= 0; i--) {
82715
83235
  const m = messages[i];
82716
83236
  if (!m || typeof m !== "object") continue;
@@ -82736,8 +83256,8 @@ var init_openclaw_runner = __esm({
82736
83256
  };
82737
83257
  extractHistoryItems = (payload) => {
82738
83258
  if (!payload || typeof payload !== "object") return [];
82739
- const wrap2 = payload;
82740
- const messages = Array.isArray(wrap2.messages) ? wrap2.messages : [];
83259
+ const wrap3 = payload;
83260
+ const messages = Array.isArray(wrap3.messages) ? wrap3.messages : [];
82741
83261
  const items = [];
82742
83262
  for (const m of messages) {
82743
83263
  if (!m || typeof m !== "object") continue;
@@ -83399,14 +83919,14 @@ var init_build_worktree = __esm({
83399
83919
  });
83400
83920
 
83401
83921
  // ../desktop_ui/device-ops/build-task.ts
83402
- var import_child_process16, import_crypto12, import_fs21, import_path36, log12, logErr7, DEFAULT_WALL_CLOCK_MS, GIT_RESERVE_MS, LINE_MAX, MILESTONE_MAX, CAVEAT_MAX, CAVEAT_LIMIT, MILESTONE_EVENT_NAME, clip, blocked, remoteMatchesRepo, resolveBusinessRepoPath, APPROVAL_MARKER, approvalRequestLine, isBranchMovedRejection, CAVEATS_MARKER, ACCEPTANCE_COMPLETE_MARKER, reportsAcceptanceComplete, CAVEAT_OPENERS, CAVEAT_PHRASES, WEAK_CAVEAT_PHRASES, ADMISSION_SUBJECT, stripDecoration, sentencesOf, caveatKey, NEAR_DUPLICATE_MIN, nearlyIdentical, collectBuildCaveats, caveatsMarkerLine, withMintedToken2, runClaudeCli, isStringKeyedObject, codexProgressFromJsonLine, codexFinalAssistantTextFromJsonLine, runCodexCli, jsonObject, withTrustedProject, alreadyTrusted, preTrustWorkspace, claudeConfigEnv, buildPrompt, runBuildDelegation, wallClockCapMs;
83922
+ var import_child_process16, import_crypto13, import_fs21, import_path36, log12, logErr7, DEFAULT_WALL_CLOCK_MS, GIT_RESERVE_MS, LINE_MAX, MILESTONE_MAX, CAVEAT_MAX, CAVEAT_LIMIT, MILESTONE_EVENT_NAME, clip, blocked, remoteMatchesRepo, resolveBusinessRepoPath, APPROVAL_MARKER, approvalRequestLine, isBranchMovedRejection, CAVEATS_MARKER, ACCEPTANCE_COMPLETE_MARKER, reportsAcceptanceComplete, CAVEAT_OPENERS, CAVEAT_PHRASES, WEAK_CAVEAT_PHRASES, ADMISSION_SUBJECT, stripDecoration, sentencesOf, caveatKey, NEAR_DUPLICATE_MIN, nearlyIdentical, collectBuildCaveats, caveatsMarkerLine, withMintedToken2, runClaudeCli, isStringKeyedObject, codexProgressFromJsonLine, codexFinalAssistantTextFromJsonLine, runCodexCli, jsonObject, withTrustedProject, alreadyTrusted, preTrustWorkspace, claudeConfigEnv, buildPrompt, runBuildDelegation, wallClockCapMs;
83403
83923
  var init_build_task = __esm({
83404
83924
  "../desktop_ui/device-ops/build-task.ts"() {
83405
83925
  "use strict";
83406
83926
  import_child_process16 = require("child_process");
83407
83927
  init_codex_account();
83408
83928
  init_codex_usage_policy();
83409
- import_crypto12 = require("crypto");
83929
+ import_crypto13 = require("crypto");
83410
83930
  import_fs21 = __toESM(require("fs"));
83411
83931
  import_path36 = __toESM(require("path"));
83412
83932
  init_client();
@@ -84153,7 +84673,7 @@ var init_build_task = __esm({
84153
84673
  `Starting ${executorLabel2} with up to ${Math.round(capMs / 6e4)} minutes for this work session.`
84154
84674
  );
84155
84675
  const before = await headSha(dir);
84156
- const sessionId = !useCodex && await claudeSupportsSessionId(cliPath) ? (0, import_crypto12.randomUUID)() : "";
84676
+ const sessionId = !useCodex && await claudeSupportsSessionId(cliPath) ? (0, import_crypto13.randomUUID)() : "";
84157
84677
  const transcript = useCodex ? null : attachBuildTranscript({
84158
84678
  workspaceId: payload.workspaceId,
84159
84679
  projectId: payload.projectId,
@@ -85897,11 +86417,11 @@ __export(runtime_exports, {
85897
86417
  runForever: () => runForever,
85898
86418
  uuidv5: () => uuidv5
85899
86419
  });
85900
- var import_crypto13, import_os15, import_path37, HEARTBEAT_MS, RENEW_CHECK_MS, RENEW_WITHIN_MS, log16, agentSession, uuidv5, identity, registerDevice, runForever;
86420
+ var import_crypto14, import_os15, import_path37, HEARTBEAT_MS, RENEW_CHECK_MS, RENEW_WITHIN_MS, log16, agentSession, uuidv5, identity, registerDevice, runForever;
85901
86421
  var init_runtime = __esm({
85902
86422
  "src/runtime.ts"() {
85903
86423
  "use strict";
85904
- import_crypto13 = require("crypto");
86424
+ import_crypto14 = require("crypto");
85905
86425
  import_os15 = __toESM(require("os"));
85906
86426
  import_path37 = __toESM(require("path"));
85907
86427
  init_api();
@@ -85923,7 +86443,7 @@ var init_runtime = __esm({
85923
86443
  };
85924
86444
  uuidv5 = (name5) => {
85925
86445
  const namespace = Buffer.from("6ba7b8109dad11d180b400c04fd430c8", "hex");
85926
- const hash = (0, import_crypto13.createHash)("sha1").update(namespace).update(name5).digest();
86446
+ const hash = (0, import_crypto14.createHash)("sha1").update(namespace).update(name5).digest();
85927
86447
  hash[6] = hash[6] & 15 | 80;
85928
86448
  hash[8] = hash[8] & 63 | 128;
85929
86449
  const hex = hash.subarray(0, 16).toString("hex");
@@ -86200,7 +86720,7 @@ Your code: ${bold(started.code)}
86200
86720
  });
86201
86721
 
86202
86722
  // src/index.ts
86203
- var import_crypto14 = require("crypto");
86723
+ var import_crypto15 = require("crypto");
86204
86724
  init_api();
86205
86725
  init_config();
86206
86726
 
@@ -86267,7 +86787,7 @@ var stopRunning = async (waitMs = 1e4) => {
86267
86787
 
86268
86788
  // src/index.ts
86269
86789
  init_logo();
86270
- var VERSION2 = true ? "0.1.0" : JSON.parse(
86790
+ var VERSION2 = true ? "0.1.1" : JSON.parse(
86271
86791
  fs.readFileSync(
86272
86792
  path.join(__dirname, "../../../package.json"),
86273
86793
  "utf8"
@@ -86288,10 +86808,10 @@ ${bold("Sign in")}
86288
86808
 
86289
86809
  ${bold("Talk to your co-founder")}
86290
86810
  clox Start a conversation
86291
- clox ask "<message>" One message, one reply
86811
+ clox ask "<message>" Ask, then keep talking
86292
86812
  clox businesses Your businesses
86293
86813
  clox business <id> Talk to that business's co-founder
86294
- clox business <id> "<msg>" One message to it
86814
+ clox business <id> "<msg>" Ask it, then keep talking
86295
86815
  clox project new <business id> "<what to build>"
86296
86816
  Start a project in a business
86297
86817
 
@@ -86312,13 +86832,20 @@ var print2 = (flags, data, human) => {
86312
86832
  else human();
86313
86833
  };
86314
86834
  var table = (rows) => {
86835
+ const cells = rows.map((row) => row.map((cell) => [...cell].length));
86315
86836
  const widths = rows[0].map(
86316
- (_, col) => Math.max(...rows.map((row) => row[col].length))
86837
+ (_, col) => Math.max(...cells.map((row) => row[col]))
86317
86838
  );
86318
- rows.forEach((row, index) => {
86319
- const line = row.map((cell, col) => cell.padEnd(widths[col])).join(" ");
86320
- console.log(index === 0 ? dim(line) : line);
86321
- });
86839
+ const rule = (l, m, r) => dim(l + widths.map((w) => "\u2500".repeat(w + 2)).join(m) + r);
86840
+ const line = (row, index) => dim("\u2502") + row.map((cell, col) => {
86841
+ const pad = " ".repeat(widths[col] - cells[index][col]);
86842
+ return ` ${index === 0 ? bold(cell) : cell}${pad} `;
86843
+ }).join(dim("\u2502")) + dim("\u2502");
86844
+ console.log(rule("\u256D", "\u252C", "\u256E"));
86845
+ console.log(line(rows[0], 0));
86846
+ console.log(rule("\u251C", "\u253C", "\u2524"));
86847
+ rows.slice(1).forEach((row, i) => console.log(line(row, i + 1)));
86848
+ console.log(rule("\u2570", "\u2534", "\u256F"));
86322
86849
  };
86323
86850
  var DEVICES = `query CliDevices {
86324
86851
  remoteDevices { deviceId label model online executors }
@@ -86335,7 +86862,7 @@ var devices = async (config2, flags) => {
86335
86862
  return;
86336
86863
  }
86337
86864
  table([
86338
- ["DEVICE", "STATUS", "CAN RUN", "ID"],
86865
+ ["Computer", "Status", "Can run", "ID"],
86339
86866
  ...data.remoteDevices.map((device) => [
86340
86867
  device.label,
86341
86868
  device.online ? "connected" : "offline",
@@ -86363,7 +86890,7 @@ var tasks = async (config2, flags) => {
86363
86890
  return;
86364
86891
  }
86365
86892
  table([
86366
- ["ID", "STATUS", "UPDATED", "TITLE"],
86893
+ ["ID", "Status", "Updated", "Task"],
86367
86894
  ...rows.slice(0, 30).map((task2) => [
86368
86895
  task2.id,
86369
86896
  task2.status.toLowerCase(),
@@ -86413,8 +86940,9 @@ var WORKSPACES = `query CliBusinesses($userId: String!) {
86413
86940
  }`;
86414
86941
  var listBusinesses = async (config2) => {
86415
86942
  const data = await gql(config2, WORKSPACES, { userId: config2.userId });
86416
- return data.workspaces.edges.map((edge) => edge.node);
86943
+ return data.workspaces.edges.map((edge) => edge.node).filter((node) => !!node.status);
86417
86944
  };
86945
+ var statusWords = (status4) => ({ "plan-approved": "Building", live: "Live", mvp: "First version" })[status4] ?? status4.replace(/-/g, " ");
86418
86946
  var businesses = async (config2, flags) => {
86419
86947
  const rows = await listBusinesses(config2);
86420
86948
  print2(flags, rows, () => {
@@ -86423,12 +86951,12 @@ var businesses = async (config2, flags) => {
86423
86951
  return;
86424
86952
  }
86425
86953
  table([
86426
- ["NAME", "STATUS", "SITE", "ID"],
86954
+ ["Business", "Status", "Website", "ID"],
86427
86955
  ...rows.map((b) => [
86428
86956
  b.name.slice(0, 32),
86429
- b.status,
86430
- b.deployUrl || b.stagingUrl || "",
86431
- b.id
86957
+ statusWords(b.status),
86958
+ (b.deployUrl || b.stagingUrl || "").replace(/^https?:\/\//, ""),
86959
+ b.id.slice(0, 8)
86432
86960
  ])
86433
86961
  ]);
86434
86962
  });
@@ -86448,14 +86976,11 @@ var findBusiness = async (config2, wanted) => {
86448
86976
  var talk = async (config2, flags, conversation, title, message) => {
86449
86977
  if (!config2.token) throw new CliError("You are signed out. Run: clox login");
86450
86978
  const chat = await Promise.resolve().then(() => (init_chat(), chat_exports));
86451
- if (!message) {
86452
- if (!process.stdin.isTTY) {
86453
- throw new CliError('Give a message: clox ask "..."');
86454
- }
86455
- console.log(logo());
86456
- console.log();
86457
- return chat.converse(config2, conversation, title);
86979
+ if (!flags.json && process.stdin.isTTY && process.stdout.isTTY) {
86980
+ const { chatScreen: chatScreen2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
86981
+ return chatScreen2(config2, conversation, title, message);
86458
86982
  }
86983
+ if (!message) throw new CliError('Give a message: clox ask "..."');
86459
86984
  if (flags.json) {
86460
86985
  const reply = await chat.sendMessage(config2, conversation, message);
86461
86986
  console.log(JSON.stringify(reply, null, 2));
@@ -86611,7 +87136,7 @@ var main = async () => {
86611
87136
  config2,
86612
87137
  flags,
86613
87138
  // One conversation per sitting: each `clox` starts a fresh one.
86614
- { version: "v5", mode: "ask", threadId: (0, import_crypto14.randomUUID)() },
87139
+ { version: "v5", mode: "ask", threadId: (0, import_crypto15.randomUUID)() },
86615
87140
  "Your co-founder",
86616
87141
  rest.join(" ")
86617
87142
  );