File size: 7,165 Bytes
c0af099
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import { spawn } from "node:child_process";
import { mkdirSync } from "node:fs";
import path from "node:path";
import process from "node:process";
import { setTimeout as delay } from "node:timers/promises";
import { pathToFileURL } from "node:url";

import {
  buildAgentServerCommand,
  buildAgentServerEnv,
  buildSafeDevConfig,
  formatMissingUvxGuidance,
  validateLocalAgentServerPath,
} from "./dev-safe.mjs";
import {
  getProcessTreeSpawnOptions,
  isProcessRunning,
  signalProcessTree,
} from "./dev-process-utils.mjs";

const DEFAULT_EXTRA_BACKEND_PORT = 18002;
const DEFAULT_EXTRA_VSCODE_PORT = 18003;
const DEFAULT_WAIT_TIMEOUT_MS = 30_000;

function parsePort(value, fallback) {
  if (value == null || value === "") {
    return fallback;
  }

  const parsed = Number.parseInt(value, 10);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    throw new Error(`Invalid port: ${value}`);
  }

  return parsed;
}

/**
 * Build a config for an *extra* standalone agent-server that shares the
 * bundled instance's persistence (state dir, conversations, secret key)
 * but listens on a different backend + vscode port.
 *
 * @param {string} cwd
 * @param {Record<string, string | undefined>} env
 */
export function buildExtraBackendConfig(
  cwd = process.cwd(),
  env = process.env,
) {
  const base = buildSafeDevConfig(cwd, env);

  const backendPort = parsePort(
    env.OH_CANVAS_EXTRA_BACKEND_PORT,
    DEFAULT_EXTRA_BACKEND_PORT,
  );
  const vscodePort = parsePort(
    env.OH_CANVAS_EXTRA_VSCODE_PORT,
    DEFAULT_EXTRA_VSCODE_PORT,
  );

  return {
    ...base,
    backendPort,
    vscodePort,
    backendBaseUrl: `http://127.0.0.1:${backendPort}`,
    backendHost: `127.0.0.1:${backendPort}`,
  };
}

function isEnoentError(error) {
  return Boolean(
    (error &&
      typeof error === "object" &&
      "code" in error &&
      error.code === "ENOENT") ||
    /ENOENT/.test(String(error)),
  );
}

async function waitForServer(url, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS) {
  const startedAt = Date.now();

  while (Date.now() - startedAt < timeoutMs) {
    try {
      const response = await fetch(url);
      if (response.ok) {
        return;
      }
    } catch {
      // Keep polling until timeout.
    }

    await delay(500);
  }

  throw new Error(`Timed out waiting for agent-server at ${url}`);
}

function spawnProcess(command, args, options = {}) {
  const child = spawn(
    command,
    args,
    getProcessTreeSpawnOptions({
      stdio: "inherit",
      ...options,
    }),
  );

  child.once("error", (error) => {
    if (isEnoentError(error) && command === "uvx") {
      console.error(formatMissingUvxGuidance(options?.cwd));
    } else if (isEnoentError(error)) {
      console.error(
        `Failed to start ${command}. Make sure it is installed and on your PATH.`,
      );
    } else {
      console.error(`Failed to start ${command}:`, error);
    }
  });

  return child;
}

async function main() {
  const config = buildExtraBackendConfig();

  if (process.env.OH_AGENT_SERVER_LOCAL_PATH) {
    validateLocalAgentServerPath(process.env.OH_AGENT_SERVER_LOCAL_PATH);
  }

  for (const dir of [
    config.stateDir,
    config.tmuxTmpDir,
    config.conversationsPath,
    config.workspacesPath,
    config.bashEventsDir,
  ]) {
    mkdirSync(dir, { recursive: true });
  }

  const agentServerCmd = buildAgentServerCommand();

  const secretKeySource = process.env.OH_SECRET_KEY
    ? "custom (from OH_SECRET_KEY)"
    : "default (for local development)";

  console.log("Starting EXTRA standalone agent-server (shared state)...");
  console.log(`- agent-server: ${agentServerCmd.source}`);
  console.log(`- backend: ${config.backendBaseUrl}`);
  console.log(`- vscode port: ${config.vscodePort}`);
  console.log(`- shared state dir: ${config.stateDir}`);
  console.log(`- shared conversations: ${config.conversationsPath}`);
  console.log(`- secret key: ${secretKeySource}`);
  console.log("");
  console.log(
    "Connect via the GUI: open Add Backend, enter " +
      `${config.backendBaseUrl} as the host. Leave the API key blank ` +
      "unless this server is started with OH_SESSION_API_KEYS_0 set.",
  );
  console.log("");

  const backend = spawnProcess(
    agentServerCmd.command,
    [
      ...agentServerCmd.args,
      "--host",
      "127.0.0.1",
      "--port",
      String(config.backendPort),
    ],
    {
      cwd: config.cwd,
      env: {
        // Deliberately not opting into the editor path prefix. This server is
        // reached by registering it as an extra backend from a browser whose
        // origin belongs to some *other* stack, so a prefix on that origin
        // either does not resolve or — worse — resolves to the bundled
        // stack's editor, silently handing back a different container's
        // workspace. No single global prefix can disambiguate the two, so this
        // launcher stays out of prefix-mode; the editor button is unavailable
        // for conversations on an extra backend.
        ...process.env,
        ...buildAgentServerEnv(config),
      },
    },
  );

  let shuttingDown = false;

  const shutdown = (signal = "SIGTERM") => {
    if (shuttingDown) {
      return;
    }

    shuttingDown = true;
    signalProcessTree(backend, signal);

    setTimeout(() => {
      if (isProcessRunning(backend)) {
        signalProcessTree(backend, "SIGKILL");
      }
      process.exit(process.exitCode ?? 0);
    }, 3000);
  };

  process.on("SIGINT", () => shutdown("SIGINT"));
  process.on("SIGTERM", () => shutdown("SIGTERM"));
  // The agent-server is spawned detached, so a SIGHUP that kills this launcher
  // (terminal or multiplexer death) would otherwise leave it running and holding
  // its port. Forward SIGTERM rather than SIGHUP: uvicorn only handles
  // SIGINT/SIGTERM, so a forwarded SIGHUP would terminate the agent-server by
  // default action instead of shutting it down gracefully.
  process.on("SIGHUP", () => shutdown("SIGTERM"));

  const backendErrored = new Promise((_, reject) => {
    backend.once("error", (error) => reject(error));
  });
  const backendExited = new Promise((_, reject) => {
    backend.once("exit", (code, signal) => {
      if (!shuttingDown) {
        reject(
          new Error(
            `agent-server exited before startup completed (code=${code ?? "null"}, signal=${signal ?? "null"})`,
          ),
        );
      }
    });
  });

  try {
    await Promise.race([
      waitForServer(`${config.backendBaseUrl}/server_info`),
      backendErrored,
      backendExited,
    ]);
  } catch (error) {
    shutdown();
    throw error;
  }

  console.log(`Extra agent-server is ready at ${config.backendBaseUrl}.`);

  backend.once("exit", (code) => {
    if (!shuttingDown) {
      console.error(`agent-server exited unexpectedly with code ${code ?? 0}`);
      shutdown();
      process.exitCode = code ?? 1;
    } else {
      process.exitCode = code ?? 0;
    }
  });
}

if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  main().catch((error) => {
    console.error(error instanceof Error ? error.message : error);
    process.exit(1);
  });
}