tencil 0.9.0 → 0.11.0

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.
@@ -1,14 +1,15 @@
1
1
  import { z } from "zod";
2
2
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
3
- import { existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { accessSync, constants, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { access, chmod, mkdir, readFile, readlink, realpath, rename, writeFile } from "node:fs/promises";
5
5
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
- import { promisify } from "node:util";
6
+ import { promisify, stripVTControlCharacters } from "node:util";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { homedir } from "node:os";
9
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { createServer } from "node:http";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
+ import { createInterface } from "node:readline";
12
13
  import { WebSocket as WebSocket$1, WebSocketServer } from "ws";
13
14
  //#region ../protocol/src/context.ts
14
15
  /** A resolved source location for the element, usually from React's owner stack. */
@@ -112,6 +113,42 @@ const BuildInfo = z.object({
112
113
  branch: z.string().min(1).max(255),
113
114
  sha: z.string().min(7).max(64)
114
115
  });
116
+ /** A key combination, matched by key position (`code`) so it works on any layout. */
117
+ const Shortcut = z.object({
118
+ code: z.string().min(1).max(32),
119
+ /** What the layout prints for it, for labels. */
120
+ key: z.string().min(1).max(32),
121
+ alt: z.boolean(),
122
+ ctrl: z.boolean(),
123
+ meta: z.boolean(),
124
+ shift: z.boolean()
125
+ });
126
+ const Shortcuts = z.object({
127
+ comment: Shortcut.nullable(),
128
+ ruler: Shortcut.nullable(),
129
+ hidePins: Shortcut.nullable(),
130
+ /** Never cleared: it's the only way back to a hidden dock. */
131
+ hideDock: Shortcut,
132
+ /** Held, not pressed. */
133
+ measure: z.enum([
134
+ "Alt",
135
+ "Control",
136
+ "Meta",
137
+ "Shift"
138
+ ]).nullable()
139
+ });
140
+ /**
141
+ * The person's own overlay settings, the same in every project on the machine.
142
+ * Saved by the local daemon; unset ones fall back to the overlay's defaults.
143
+ */
144
+ const Preferences = z.object({
145
+ theme: z.enum([
146
+ "dark",
147
+ "light",
148
+ "system"
149
+ ]).optional(),
150
+ shortcuts: Shortcuts.optional()
151
+ });
115
152
  const ClientMessage = z.discriminatedUnion("type", [
116
153
  z.object({
117
154
  type: z.literal("hello"),
@@ -158,6 +195,7 @@ const ClientMessage = z.discriminatedUnion("type", [
158
195
  }),
159
196
  z.object({ type: z.literal("provider.threads") }),
160
197
  z.object({ type: z.literal("provider.models") }),
198
+ z.object({ type: z.literal("project.choices") }),
161
199
  z.object({
162
200
  type: z.literal("project.select"),
163
201
  root: z.string().min(1)
@@ -197,7 +235,11 @@ const ClientMessage = z.discriminatedUnion("type", [
197
235
  type: z.literal("model.select"),
198
236
  model: z.string().min(1).nullable()
199
237
  }),
200
- z.object({ type: z.literal("update.start") })
238
+ z.object({ type: z.literal("update.start") }),
239
+ z.object({
240
+ type: z.literal("preferences.update"),
241
+ preferences: Preferences
242
+ })
201
243
  ]);
202
244
  z.object({
203
245
  id: z.string(),
@@ -230,6 +272,27 @@ z.object({
230
272
  /** The toolbar offers the ruler: spacing while picking, distances with Alt. */
231
273
  ruler: z.boolean()
232
274
  });
275
+ /**
276
+ * How the daemon matched the page to its project: an Ensemble thread's dev
277
+ * server, the git root the Vite or Next plugin passed, the dev server listening
278
+ * on the page's port, the Docker container publishing it, or a pick in the overlay.
279
+ */
280
+ const DetectedVia = z.enum([
281
+ "ensemble",
282
+ "plugin",
283
+ "port",
284
+ "docker"
285
+ ]);
286
+ z.object({
287
+ via: z.enum([...DetectedVia.options, "picked"]),
288
+ port: z.number().int().optional(),
289
+ /** Picked over a project Tencil did detect: that one, to go back to. */
290
+ detected: z.object({
291
+ root: z.string(),
292
+ via: DetectedVia,
293
+ port: z.number().int().optional()
294
+ }).optional()
295
+ });
233
296
  //#endregion
234
297
  //#region ../protocol/src/thread.ts
235
298
  /**
@@ -657,6 +720,8 @@ var Bridge = class {
657
720
  return;
658
721
  }
659
722
  case "update.start": throw new Error("Tencil can't update itself here");
723
+ case "preferences.update": throw new Error("Preferences aren't saved here");
724
+ case "project.choices": throw new Error("Projects can't be switched here");
660
725
  }
661
726
  } catch (error) {
662
727
  const threadId = "threadId" in message ? message.threadId : void 0;
@@ -1412,7 +1477,7 @@ var EnsembleClient = class {
1412
1477
  throw response.status === 401 ? new EnsembleUnauthorizedError(reason) : new EnsembleHttpError(response.status, reason);
1413
1478
  }
1414
1479
  };
1415
- function errorMessage$2(error) {
1480
+ function errorMessage$3(error) {
1416
1481
  return error instanceof Error ? error.message : String(error);
1417
1482
  }
1418
1483
  function threadPath(threadId) {
@@ -1665,7 +1730,7 @@ var ThreadFeed = class {
1665
1730
  type: "archived",
1666
1731
  threadId: this.threadId
1667
1732
  });
1668
- this.options.log?.(`Reconnecting to Ensemble's feed: ${errorMessage$2(error)}`);
1733
+ this.options.log?.(`Reconnecting to Ensemble's feed: ${errorMessage$3(error)}`);
1669
1734
  }
1670
1735
  await setTimeout$1(delayMs, void 0, {
1671
1736
  signal,
@@ -1930,7 +1995,7 @@ var EnsembleProvider = class {
1930
1995
  state: "unavailable",
1931
1996
  detail: "This Ensemble thread is closed. Choose an open one."
1932
1997
  });
1933
- this.#retryLater(`Ensemble didn't answer: ${errorMessage$2(error)}`);
1998
+ this.#retryLater(`Ensemble didn't answer: ${errorMessage$3(error)}`);
1934
1999
  }
1935
2000
  }
1936
2001
  async #pair() {
@@ -1945,7 +2010,7 @@ var EnsembleProvider = class {
1945
2010
  this.#setInfo({
1946
2011
  state: "unauthorized",
1947
2012
  canPair: true,
1948
- detail: errorMessage$2(error)
2013
+ detail: errorMessage$3(error)
1949
2014
  });
1950
2015
  throw error;
1951
2016
  }
@@ -2028,38 +2093,90 @@ const defaultExec = async (command, args) => (await run$1(command, args, {
2028
2093
  timeout: 3e3,
2029
2094
  windowsHide: true
2030
2095
  })).stdout;
2031
- /**
2032
- * Works out which project folder a page belongs to:
2033
- * 1. the Ensemble thread whose dev server listens on the port,
2034
- * 2. the repository root the Vite or Next loader sent, if it's a git checkout,
2035
- * 3. the dev server's working directory, found from the port it listens on,
2036
- * 4. what the user picked for this address before (a folder or an Ensemble thread).
2037
- * Picks come last: ports get reused (5173 is every Vite app's default), so a pick
2038
- * only stands in for what can't be detected. Returns undefined when nothing works;
2039
- * the overlay then asks.
2040
- */
2096
+ function pickKey(origin, detected) {
2097
+ return `${origin} ${detected}`;
2098
+ }
2041
2099
  var ProjectResolver = class {
2042
2100
  #memory;
2101
+ /** Picks made over a detected project, by address and that project. */
2102
+ #picks;
2043
2103
  #exec;
2044
2104
  #platform;
2045
2105
  #ensembleForPort;
2046
2106
  constructor(options) {
2047
2107
  this.#memory = new OriginMemory(join(options.dataDir, "origins.json"));
2108
+ this.#picks = new OriginMemory(join(options.dataDir, "project-picks.json"));
2048
2109
  this.#exec = options.exec ?? defaultExec;
2049
2110
  this.#platform = options.platform ?? process.platform;
2050
2111
  this.#ensembleForPort = options.ensembleForPort;
2051
2112
  }
2052
2113
  async resolve(pageUrl, claimedRoot) {
2114
+ return (await this.detect(pageUrl, claimedRoot))?.root;
2115
+ }
2116
+ /**
2117
+ * The page's project and how it was found. A pick made over a detected
2118
+ * project only holds while that same project is detected on the address:
2119
+ * when another app takes the port, detection wins again.
2120
+ */
2121
+ async detect(pageUrl, claimedRoot) {
2053
2122
  const origin = safeOrigin(pageUrl);
2054
2123
  if (!origin) return void 0;
2124
+ const found = await this.#automatic(origin, claimedRoot);
2125
+ if (found) {
2126
+ const picked = await this.#picks.get(pickKey(origin, found.root));
2127
+ if (!(picked && (ensembleThreadId(picked) || existsSync(picked))) || picked === found.root) return found;
2128
+ return {
2129
+ root: picked,
2130
+ source: {
2131
+ via: "picked",
2132
+ detected: {
2133
+ root: found.root,
2134
+ ...found.source
2135
+ }
2136
+ }
2137
+ };
2138
+ }
2139
+ const remembered = await this.#memory.get(origin);
2140
+ return remembered && (ensembleThreadId(remembered) || existsSync(remembered)) ? {
2141
+ root: remembered,
2142
+ source: { via: "picked" }
2143
+ } : void 0;
2144
+ }
2145
+ /** Detection alone: Ensemble thread, the plugin's git root, then the port. */
2146
+ async #automatic(origin, claimedRoot) {
2055
2147
  const port = portOf(origin);
2056
2148
  const thread = port ? await this.#ensembleForPort?.(port).catch(() => void 0) : void 0;
2057
- if (thread) return thread;
2058
- if (claimedRoot && isGitRoot(claimedRoot)) return resolve(claimedRoot);
2059
- const folder = port ? await this.folderForPort(port).catch(() => void 0) : void 0;
2060
- if (folder) return projectRoot(folder);
2061
- const remembered = await this.#memory.get(origin);
2062
- return remembered && (ensembleThreadId(remembered) || existsSync(remembered)) ? remembered : void 0;
2149
+ if (thread) return {
2150
+ root: thread,
2151
+ source: {
2152
+ via: "ensemble",
2153
+ port
2154
+ }
2155
+ };
2156
+ if (claimedRoot && isGitRoot(claimedRoot)) return {
2157
+ root: resolve(claimedRoot),
2158
+ source: { via: "plugin" }
2159
+ };
2160
+ const found = port ? await this.#portFolder(port).catch(() => void 0) : void 0;
2161
+ if (!found || !port) return void 0;
2162
+ return {
2163
+ root: projectRoot(found.folder),
2164
+ source: {
2165
+ via: found.docker ? "docker" : "port",
2166
+ port
2167
+ }
2168
+ };
2169
+ }
2170
+ /**
2171
+ * Use `root` for this address while `detected` is what Tencil finds there
2172
+ * (the overlay's Change). Picking the detected project itself undoes it.
2173
+ */
2174
+ async pick(pageUrl, detected, root) {
2175
+ const origin = safeOrigin(pageUrl);
2176
+ if (!origin) return;
2177
+ const key = pickKey(origin, detected);
2178
+ if (projectKey(root) === detected) await this.#picks.delete(key);
2179
+ else await this.#picks.set(key, projectKey(root));
2063
2180
  }
2064
2181
  /** Remember the user's choice for an address (from the overlay's project picker). */
2065
2182
  remember(pageUrl, root) {
@@ -2071,20 +2188,36 @@ var ProjectResolver = class {
2071
2188
  * package. When Docker publishes the port, the compose project of the container.
2072
2189
  */
2073
2190
  async folderForPort(port) {
2191
+ return (await this.#portFolder(port))?.folder;
2192
+ }
2193
+ async #portFolder(port) {
2194
+ const docker = async () => {
2195
+ const folder = await this.#composeFolder(port);
2196
+ return folder ? {
2197
+ folder,
2198
+ docker: true
2199
+ } : void 0;
2200
+ };
2074
2201
  const pids = await this.#listeners(port);
2075
- if (pids.length === 0 && this.#platform === "linux") return this.#composeFolder(port);
2202
+ if (pids.length === 0 && this.#platform === "linux") return docker();
2076
2203
  for (const pid of pids) {
2077
2204
  const cwd = await this.#cwd(pid).catch(() => void 0);
2078
- if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return cwd;
2205
+ if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return {
2206
+ folder: cwd,
2207
+ docker: false
2208
+ };
2079
2209
  const commandLine = await this.#commandLine(pid).catch(() => "");
2080
- if (isDockerForwarder(commandLine)) return this.#composeFolder(port);
2210
+ if (isDockerForwarder(commandLine)) return docker();
2081
2211
  const fromCommand = projectFromCommandLine(commandLine);
2082
- if (fromCommand) return fromCommand;
2212
+ if (fromCommand) return {
2213
+ folder: fromCommand,
2214
+ docker: false
2215
+ };
2083
2216
  }
2084
2217
  }
2085
2218
  /** Working directory of the compose project whose container publishes `port`. */
2086
2219
  async #composeFolder(port) {
2087
- return firstLine(await this.#exec("docker", [
2220
+ return firstLine$1(await this.#exec("docker", [
2088
2221
  "ps",
2089
2222
  "--filter",
2090
2223
  `publish=${port}`,
@@ -2187,7 +2320,7 @@ function isDockerForwarder(commandLine) {
2187
2320
  function projectFromCommandLine(commandLine) {
2188
2321
  return commandLine.match(/(?:^|[\s"'])((?:[A-Za-z]:)?[\\/][^\s"']*?)[\\/]node_modules[\\/]/)?.[1];
2189
2322
  }
2190
- function firstLine(output) {
2323
+ function firstLine$1(output) {
2191
2324
  return output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
2192
2325
  }
2193
2326
  function safeOrigin(pageUrl) {
@@ -2214,6 +2347,15 @@ var OriginMemory = class {
2214
2347
  async set(origin, root) {
2215
2348
  const all = await this.#read();
2216
2349
  all[origin] = root;
2350
+ await this.#write(all);
2351
+ }
2352
+ async delete(origin) {
2353
+ const all = await this.#read();
2354
+ if (!(origin in all)) return;
2355
+ delete all[origin];
2356
+ await this.#write(all);
2357
+ }
2358
+ async #write(all) {
2217
2359
  await mkdir(dirname(this.path), { recursive: true });
2218
2360
  await writeFile(this.path, `${JSON.stringify(all, null, 2)}\n`);
2219
2361
  }
@@ -2320,7 +2462,7 @@ async function installAgentSdk(installDir) {
2320
2462
  * the same id the transcript on disk carries, so a replay lines up with them.
2321
2463
  * Subagent output and tool results stay out: the overlay shows the conversation.
2322
2464
  */
2323
- var TurnTracker = class {
2465
+ var TurnTracker$1 = class {
2324
2466
  #drafts = /* @__PURE__ */ new Map();
2325
2467
  #current;
2326
2468
  #status = { status: "idle" };
@@ -2493,7 +2635,7 @@ function toMessage(draft) {
2493
2635
  }
2494
2636
  //#endregion
2495
2637
  //#region ../provider-claude-code/src/claude-code-provider.ts
2496
- const DEFAULT_IDLE_CLOSE_MS = 6e5;
2638
+ const DEFAULT_IDLE_CLOSE_MS$1 = 6e5;
2497
2639
  /**
2498
2640
  * Runs Claude Code through the Agent SDK. Unlike T3 Code there is no server
2499
2641
  * holding the conversation: the daemon hosts one Claude Code process per
@@ -2530,7 +2672,7 @@ var ClaudeCodeProvider = class {
2530
2672
  this.#sdk = void 0;
2531
2673
  this.#setInfo({
2532
2674
  state: "unavailable",
2533
- detail: errorMessage$1(error)
2675
+ detail: errorMessage$2(error)
2534
2676
  });
2535
2677
  }
2536
2678
  }
@@ -2591,7 +2733,7 @@ var ClaudeCodeProvider = class {
2591
2733
  for (const message of messages) sink.message(message);
2592
2734
  const status = this.#status(session.id);
2593
2735
  sink.status(status.status, status.detail);
2594
- }, (error) => this.#log(`Couldn't load session ${providerThreadId}: ${errorMessage$1(error)}`));
2736
+ }, (error) => this.#log(`Couldn't load session ${providerThreadId}: ${errorMessage$2(error)}`));
2595
2737
  return () => {
2596
2738
  if (session.sink === sink) session.sink = void 0;
2597
2739
  };
@@ -2613,7 +2755,7 @@ var ClaudeCodeProvider = class {
2613
2755
  if (!session) {
2614
2756
  session = {
2615
2757
  id,
2616
- tracker: new TurnTracker(),
2758
+ tracker: new TurnTracker$1(),
2617
2759
  messages: /* @__PURE__ */ new Map()
2618
2760
  };
2619
2761
  this.#sessions.set(id, session);
@@ -2688,7 +2830,7 @@ var ClaudeCodeProvider = class {
2688
2830
  if (update.turnEnded) this.#scheduleIdleClose(session, run);
2689
2831
  }
2690
2832
  } catch (error) {
2691
- failure = errorMessage$1(error);
2833
+ failure = errorMessage$2(error);
2692
2834
  }
2693
2835
  if (session.run !== run) return;
2694
2836
  session.run = void 0;
@@ -2738,7 +2880,7 @@ var ClaudeCodeProvider = class {
2738
2880
  if (session.tracker.status().status === "working") return;
2739
2881
  run.idleTimer = setTimeout(() => {
2740
2882
  if (session.run === run) this.#close(session);
2741
- }, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS);
2883
+ }, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS$1);
2742
2884
  run.idleTimer.unref?.();
2743
2885
  }
2744
2886
  #close(session) {
@@ -2767,7 +2909,7 @@ var ClaudeCodeProvider = class {
2767
2909
  #workspaceRoot() {
2768
2910
  this.#workspace ??= (async () => {
2769
2911
  const root = await realpath(this.#options.projectRoot).catch(() => this.#options.projectRoot);
2770
- return await repositoryRoot$1(root) ?? root;
2912
+ return await repositoryRoot$2(root) ?? root;
2771
2913
  })();
2772
2914
  return this.#workspace;
2773
2915
  }
@@ -2797,14 +2939,14 @@ function imageBlock(attachment) {
2797
2939
  };
2798
2940
  }
2799
2941
  /** The nearest folder at or above `dir` with a `.git` entry, if any. */
2800
- async function repositoryRoot$1(dir) {
2942
+ async function repositoryRoot$2(dir) {
2801
2943
  for (let current = dir;; current = dirname(current)) {
2802
- if (await exists$1(join(current, ".git"))) return current;
2944
+ if (await exists$2(join(current, ".git"))) return current;
2803
2945
  if (dirname(current) === current) return void 0;
2804
2946
  }
2805
2947
  }
2806
- const exists$1 = (path) => access(path).then(() => true, () => false);
2807
- function errorMessage$1(error) {
2948
+ const exists$2 = (path) => access(path).then(() => true, () => false);
2949
+ function errorMessage$2(error) {
2808
2950
  return error instanceof Error ? error.message : String(error);
2809
2951
  }
2810
2952
  //#endregion
@@ -2825,6 +2967,1057 @@ async function listClaudeCodeProjects(options) {
2825
2967
  return projects;
2826
2968
  }
2827
2969
  //#endregion
2970
+ //#region ../provider-codex/src/app-server.ts
2971
+ function spawnAppServer(command) {
2972
+ const shell = /\.(cmd|bat)$/i.test(command);
2973
+ return spawn(shell ? `"${command}"` : command, ["app-server"], {
2974
+ stdio: "pipe",
2975
+ shell,
2976
+ windowsHide: true
2977
+ });
2978
+ }
2979
+ var RpcError$1 = class extends Error {
2980
+ code;
2981
+ constructor(code, message) {
2982
+ super(message);
2983
+ this.code = code;
2984
+ this.name = "RpcError";
2985
+ }
2986
+ };
2987
+ const METHOD_NOT_FOUND = -32601;
2988
+ /** Starting a thread waits for the user's MCP servers, so this is generous. */
2989
+ const REQUEST_TIMEOUT_MS = 12e4;
2990
+ /** How long a closed server gets to finish on its own before it's killed. */
2991
+ const CLOSE_GRACE_MS = 2e3;
2992
+ const EXIT_DRAIN_MS = 200;
2993
+ /** JSON-RPC with `codex app-server`: one JSON message per line over stdio. */
2994
+ var AppServer = class {
2995
+ #process;
2996
+ #handlers;
2997
+ #pending = /* @__PURE__ */ new Map();
2998
+ #nextId = 1;
2999
+ #closed = false;
3000
+ #lastError = "";
3001
+ constructor(process, handlers) {
3002
+ this.#process = process;
3003
+ this.#handlers = handlers;
3004
+ process.stdin.on("error", () => {});
3005
+ process.once("error", (error) => this.#ended(error.message));
3006
+ process.once("close", () => this.#ended());
3007
+ process.once("exit", () => setTimeout(() => this.#ended(), EXIT_DRAIN_MS).unref?.());
3008
+ createInterface({ input: process.stdout }).on("line", (line) => this.#receive(line));
3009
+ if (process.stderr) createInterface({ input: process.stderr }).on("line", (line) => {
3010
+ const text = stripVTControlCharacters(line).trim();
3011
+ if (!text) return;
3012
+ this.#lastError = text;
3013
+ handlers.log(text);
3014
+ });
3015
+ }
3016
+ /** The handshake every connection starts with. */
3017
+ async initialize(version) {
3018
+ await this.request("initialize", {
3019
+ clientInfo: {
3020
+ name: "tencil",
3021
+ title: "Tencil",
3022
+ version
3023
+ },
3024
+ capabilities: {
3025
+ experimentalApi: false,
3026
+ requestAttestation: false
3027
+ }
3028
+ });
3029
+ this.#write({ method: "initialized" });
3030
+ }
3031
+ request(method, params) {
3032
+ if (this.#closed) return Promise.reject(new Error(this.#stoppedMessage()));
3033
+ return new Promise((resolve, reject) => {
3034
+ const id = this.#nextId++;
3035
+ const timer = setTimeout(() => {
3036
+ this.#pending.delete(id);
3037
+ reject(/* @__PURE__ */ new Error(`Codex didn't answer ${method} in time`));
3038
+ }, REQUEST_TIMEOUT_MS);
3039
+ timer.unref?.();
3040
+ this.#pending.set(id, {
3041
+ resolve: (result) => resolve(result),
3042
+ reject,
3043
+ timer
3044
+ });
3045
+ this.#write({
3046
+ method,
3047
+ id,
3048
+ params
3049
+ });
3050
+ });
3051
+ }
3052
+ /** Ending stdin stops the server; kill it if it doesn't. */
3053
+ close() {
3054
+ if (this.#closed) return;
3055
+ this.#process.stdin.end();
3056
+ const timer = setTimeout(() => this.#process.kill(), CLOSE_GRACE_MS);
3057
+ timer.unref?.();
3058
+ this.#process.once("exit", () => clearTimeout(timer));
3059
+ }
3060
+ #receive(line) {
3061
+ let message;
3062
+ try {
3063
+ message = JSON.parse(line);
3064
+ } catch {
3065
+ this.#handlers.log(`Unreadable message from Codex: ${line.slice(0, 200)}`);
3066
+ return;
3067
+ }
3068
+ if (message.method && message.id !== void 0) {
3069
+ this.#answer(message.id, message.method, message.params);
3070
+ return;
3071
+ }
3072
+ if (message.method) {
3073
+ try {
3074
+ this.#handlers.notification(message.method, message.params);
3075
+ } catch (error) {
3076
+ this.#handlers.log(`Couldn't handle ${message.method}: ${errorMessage$1(error)}`);
3077
+ }
3078
+ return;
3079
+ }
3080
+ const pending = message.id === void 0 ? void 0 : this.#pending.get(message.id);
3081
+ if (!pending || message.id === void 0) return;
3082
+ this.#pending.delete(message.id);
3083
+ clearTimeout(pending.timer);
3084
+ if (message.error) pending.reject(new RpcError$1(message.error.code, message.error.message));
3085
+ else pending.resolve(message.result);
3086
+ }
3087
+ /** Every request gets an answer: an unanswered one would hang the turn. */
3088
+ #answer(id, method, params) {
3089
+ try {
3090
+ this.#write({
3091
+ id,
3092
+ result: this.#handlers.request(method, params)
3093
+ });
3094
+ } catch (error) {
3095
+ this.#write({
3096
+ id,
3097
+ error: {
3098
+ code: error instanceof RpcError$1 ? error.code : METHOD_NOT_FOUND,
3099
+ message: errorMessage$1(error)
3100
+ }
3101
+ });
3102
+ }
3103
+ }
3104
+ #write(message) {
3105
+ if (!this.#closed) this.#process.stdin.write(`${JSON.stringify(message)}\n`);
3106
+ }
3107
+ #ended(reason) {
3108
+ if (this.#closed) return;
3109
+ this.#closed = true;
3110
+ if (reason) this.#lastError = reason;
3111
+ const message = this.#stoppedMessage();
3112
+ for (const pending of this.#pending.values()) {
3113
+ clearTimeout(pending.timer);
3114
+ pending.reject(new Error(message));
3115
+ }
3116
+ this.#pending.clear();
3117
+ this.#handlers.closed();
3118
+ }
3119
+ #stoppedMessage() {
3120
+ return this.#lastError ? `Codex stopped: ${this.#lastError}` : "Codex stopped";
3121
+ }
3122
+ };
3123
+ function errorMessage$1(error) {
3124
+ return error instanceof Error ? error.message : String(error);
3125
+ }
3126
+ //#endregion
3127
+ //#region ../provider-codex/src/find-codex.ts
3128
+ const NOT_INSTALLED = "Codex isn't installed. Install it with `npm i -g @openai/codex`, then run `codex login`.";
3129
+ /** Where the Codex desktop app keeps its copy of the CLI, inside ChatGPT or its own app. */
3130
+ const APP_BINARIES = ["ChatGPT.app", "Codex.app"].map((app) => join(app, "Contents", "Resources", "codex"));
3131
+ /**
3132
+ * The Codex binary: the CLI on the PATH, otherwise the one in the desktop app.
3133
+ * Tencil never installs it. It's about 400 MB, and it's the user's own install
3134
+ * and login that pins run under, so setup says how to get it instead.
3135
+ */
3136
+ function findCodex(options = {}) {
3137
+ const platform = options.platform ?? process.platform;
3138
+ const names = platform === "win32" ? ["codex.exe", "codex.cmd"] : ["codex"];
3139
+ const onPath = ((options.env ?? process.env).PATH ?? "").split(platform === "win32" ? ";" : delimiter).filter(Boolean).flatMap((dir) => names.map((name) => join(dir, name)));
3140
+ const applications = options.applications ?? ["/Applications", join(homedir(), "Applications")];
3141
+ const inApps = platform === "darwin" ? applications.flatMap((dir) => APP_BINARIES.map((binary) => join(dir, binary))) : [];
3142
+ return [...onPath, ...inApps].find(isExecutable);
3143
+ }
3144
+ /** How to start Codex. Throws, saying how to fix it, when this machine has none. */
3145
+ function appServerSpawner(options, find = findCodex) {
3146
+ if (options.spawn) return options.spawn;
3147
+ const command = options.command ?? find();
3148
+ if (!command) throw new Error(NOT_INSTALLED);
3149
+ return () => spawnAppServer(command);
3150
+ }
3151
+ function isExecutable(path) {
3152
+ try {
3153
+ accessSync(path, constants.X_OK);
3154
+ return statSync(path).isFile();
3155
+ } catch {
3156
+ return false;
3157
+ }
3158
+ }
3159
+ //#endregion
3160
+ //#region ../provider-codex/src/tool-steps.ts
3161
+ /** `undefined` for items that aren't something Codex did: messages, bookkeeping. */
3162
+ function itemLabel(item) {
3163
+ switch (item.type) {
3164
+ case "commandExecution": return commandLabel(item);
3165
+ case "fileChange": return fileChangeLabel(item);
3166
+ case "mcpToolCall": return {
3167
+ running: `Using ${item.tool}`,
3168
+ done: `Used ${item.tool}`,
3169
+ detail: item.error?.message ?? item.server
3170
+ };
3171
+ case "dynamicToolCall": return {
3172
+ running: `Using ${item.tool}`,
3173
+ done: `Used ${item.tool}`
3174
+ };
3175
+ case "collabAgentToolCall":
3176
+ if (item.tool !== "spawnAgent") return void 0;
3177
+ return {
3178
+ running: "Delegating to a subagent",
3179
+ done: "Delegated to a subagent",
3180
+ ...item.prompt ? { detail: firstLine(item.prompt) } : {}
3181
+ };
3182
+ case "webSearch": {
3183
+ const what = item.query ? ` for ${clip(item.query, 36)}` : "";
3184
+ return {
3185
+ running: `Searching the web${what}`,
3186
+ done: `Searched the web${what}`
3187
+ };
3188
+ }
3189
+ case "imageView": {
3190
+ const file = basename$1(item.path);
3191
+ return {
3192
+ running: `Viewing ${file}`,
3193
+ done: `Viewed ${file}`
3194
+ };
3195
+ }
3196
+ case "imageGeneration": return {
3197
+ running: "Generating an image",
3198
+ done: "Generated an image"
3199
+ };
3200
+ case "contextCompaction": return {
3201
+ running: "Compacting the conversation",
3202
+ done: "Compacted the conversation"
3203
+ };
3204
+ default: return;
3205
+ }
3206
+ }
3207
+ /** What Codex is thinking about, from the summary of its reasoning: `**Heading**\n\nText`. */
3208
+ function reasoningLabel(summary) {
3209
+ const detail = firstLine(summary).replaceAll("**", "").trim();
3210
+ return detail ? {
3211
+ running: "Thinking",
3212
+ done: "Thought",
3213
+ detail
3214
+ } : void 0;
3215
+ }
3216
+ function itemStatus(item) {
3217
+ const status = "status" in item ? item.status : void 0;
3218
+ return status === "failed" || status === "declined" ? "failed" : "done";
3219
+ }
3220
+ /** The second line of a finished step: why it didn't run, if it didn't. */
3221
+ function finishedDetail(item, label) {
3222
+ return "status" in item && item.status === "declined" ? "Refused: it needs approval, and nobody is here to give it" : label.detail;
3223
+ }
3224
+ function commandLabel(item) {
3225
+ const actions = item.commandActions ?? [];
3226
+ const only = actions.length === 1 ? actions[0] : void 0;
3227
+ if (only?.type === "read") return {
3228
+ running: `Reading ${only.name}`,
3229
+ done: `Read ${only.name}`
3230
+ };
3231
+ if (only?.type === "search" && only.query) {
3232
+ const query = clip(only.query, 40);
3233
+ return {
3234
+ running: `Searching for ${query}`,
3235
+ done: `Searched for ${query}`
3236
+ };
3237
+ }
3238
+ if (only?.type === "listFiles") {
3239
+ const where = only.path ? basename$1(only.path) : "files";
3240
+ return {
3241
+ running: `Listing ${where}`,
3242
+ done: `Listed ${where}`
3243
+ };
3244
+ }
3245
+ const command = withoutShell(item.command);
3246
+ const short = clip(firstLine(command), 48);
3247
+ return {
3248
+ running: `Running ${short}`,
3249
+ done: `Ran ${short}`,
3250
+ ...short === command ? {} : { detail: command }
3251
+ };
3252
+ }
3253
+ function fileChangeLabel(item) {
3254
+ const changes = item.changes ?? [];
3255
+ const [first] = changes;
3256
+ if (changes.length === 1 && first) {
3257
+ const file = basename$1(first.path);
3258
+ if (first.kind.type === "add") return {
3259
+ running: `Creating ${file}`,
3260
+ done: `Created ${file}`
3261
+ };
3262
+ if (first.kind.type === "delete") return {
3263
+ running: `Deleting ${file}`,
3264
+ done: `Deleted ${file}`
3265
+ };
3266
+ return {
3267
+ running: `Editing ${file}`,
3268
+ done: `Edited ${file}`
3269
+ };
3270
+ }
3271
+ const count = changes.length > 1 ? `${changes.length} files` : "files";
3272
+ return {
3273
+ running: `Editing ${count}`,
3274
+ done: `Edited ${count}`,
3275
+ ...changes.length > 1 ? { detail: changes.map((change) => basename$1(change.path)).join(", ") } : {}
3276
+ };
3277
+ }
3278
+ /** `/bin/zsh -lc 'pnpm test'` is `pnpm test` to the person reading it. */
3279
+ function withoutShell(command) {
3280
+ const inner = /^\S*sh -l?c '(.*)'$/s.exec(command)?.[1];
3281
+ return inner === void 0 ? command : inner.replaceAll(`'\\''`, `'`);
3282
+ }
3283
+ function basename$1(path) {
3284
+ return path.split(/[\\/]/).pop() || path;
3285
+ }
3286
+ function firstLine(text) {
3287
+ return text.split("\n", 1)[0] ?? "";
3288
+ }
3289
+ function clip(text, max) {
3290
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
3291
+ }
3292
+ //#endregion
3293
+ //#region ../provider-codex/src/transcript.ts
3294
+ const NOT_SIGNED_IN = "Codex is not signed in. Run `codex login`.";
3295
+ const iso = (ms) => new Date(ms).toISOString();
3296
+ /**
3297
+ * Folds the notifications of one thread into cumulative `ProviderMessage`s and
3298
+ * `ThreadStep`s. Messages are keyed by the item id Codex also keeps in its
3299
+ * history (a user message by the id Tencil sent it with), so a replay lines up.
3300
+ */
3301
+ var TurnTracker = class {
3302
+ #drafts = /* @__PURE__ */ new Map();
3303
+ #steps = /* @__PURE__ */ new Map();
3304
+ /** What reasoning items have summarised so far. */
3305
+ #summaries = /* @__PURE__ */ new Map();
3306
+ #turnId;
3307
+ #status = { status: "idle" };
3308
+ status() {
3309
+ return this.#status;
3310
+ }
3311
+ setStatus(status) {
3312
+ this.#status = status;
3313
+ }
3314
+ /** The turn in progress, which `turn/interrupt` needs. */
3315
+ activeTurn() {
3316
+ return this.#turnId;
3317
+ }
3318
+ /** `turn/start` answered: the turn it started, unless its notifications got here first. */
3319
+ noteTurn(turnId) {
3320
+ if (this.#status.status === "working") this.#turnId ??= turnId;
3321
+ }
3322
+ /** The current turn's steps, for a sink that starts watching midway. */
3323
+ steps() {
3324
+ return [...this.#steps.values()];
3325
+ }
3326
+ apply(method, params, now = (/* @__PURE__ */ new Date()).toISOString()) {
3327
+ const update = {
3328
+ messages: [],
3329
+ steps: []
3330
+ };
3331
+ switch (method) {
3332
+ case "turn/started": {
3333
+ const { turn } = params;
3334
+ this.#turnId = turn.id;
3335
+ this.#steps.clear();
3336
+ this.#summaries.clear();
3337
+ update.status = { status: "working" };
3338
+ break;
3339
+ }
3340
+ case "item/started": {
3341
+ const { item, startedAtMs } = params;
3342
+ this.#itemStarted(item, startedAtMs ? iso(startedAtMs) : now, update);
3343
+ break;
3344
+ }
3345
+ case "item/agentMessage/delta": {
3346
+ const { itemId, delta } = params;
3347
+ const draft = this.#drafts.get(itemId);
3348
+ if (draft) {
3349
+ draft.text += delta;
3350
+ update.messages.push({ ...draft });
3351
+ }
3352
+ break;
3353
+ }
3354
+ case "item/reasoning/summaryTextDelta": {
3355
+ const { itemId, delta } = params;
3356
+ const summary = (this.#summaries.get(itemId) ?? "") + delta;
3357
+ this.#summaries.set(itemId, summary);
3358
+ this.#reasoning(itemId, summary, now, update);
3359
+ break;
3360
+ }
3361
+ case "item/completed": {
3362
+ const { item, completedAtMs } = params;
3363
+ this.#itemCompleted(item, completedAtMs ? iso(completedAtMs) : now, update);
3364
+ break;
3365
+ }
3366
+ case "error": {
3367
+ const { error, willRetry } = params;
3368
+ if (willRetry) update.status = {
3369
+ status: "working",
3370
+ detail: `Retrying: ${error.message}`
3371
+ };
3372
+ if (isUnauthorized(error)) update.unauthorized = NOT_SIGNED_IN;
3373
+ break;
3374
+ }
3375
+ case "turn/completed": {
3376
+ const { turn } = params;
3377
+ this.#finish(now, update);
3378
+ update.turnEnded = true;
3379
+ update.status = turn.status === "failed" ? {
3380
+ status: "error",
3381
+ detail: turn.error?.message
3382
+ } : { status: "idle" };
3383
+ if (turn.error && isUnauthorized(turn.error)) update.unauthorized = NOT_SIGNED_IN;
3384
+ break;
3385
+ }
3386
+ }
3387
+ if (update.status) this.#status = update.status;
3388
+ return update;
3389
+ }
3390
+ /** Close whatever is still open: Codex stopped before finishing the turn. */
3391
+ finish(now = (/* @__PURE__ */ new Date()).toISOString()) {
3392
+ const update = {
3393
+ messages: [],
3394
+ steps: []
3395
+ };
3396
+ this.#finish(now, update);
3397
+ return update;
3398
+ }
3399
+ #itemStarted(item, startedAt, update) {
3400
+ if (item.type === "agentMessage") {
3401
+ this.#drafts.set(item.id, {
3402
+ id: item.id,
3403
+ role: "assistant",
3404
+ text: item.text,
3405
+ streaming: true,
3406
+ createdAt: startedAt
3407
+ });
3408
+ return;
3409
+ }
3410
+ const label = itemLabel(item);
3411
+ if (!label) return;
3412
+ const step = {
3413
+ id: item.id,
3414
+ label: label.running,
3415
+ status: "running",
3416
+ ...label.detail ? { detail: label.detail } : {},
3417
+ startedAt
3418
+ };
3419
+ this.#steps.set(item.id, step);
3420
+ update.steps.push(step);
3421
+ }
3422
+ #itemCompleted(item, endedAt, update) {
3423
+ if (item.type === "agentMessage") {
3424
+ const draft = this.#drafts.get(item.id);
3425
+ this.#drafts.delete(item.id);
3426
+ if (item.text.trim()) update.messages.push({
3427
+ id: item.id,
3428
+ role: "assistant",
3429
+ text: item.text,
3430
+ streaming: false,
3431
+ createdAt: draft?.createdAt ?? endedAt
3432
+ });
3433
+ return;
3434
+ }
3435
+ if (item.type === "reasoning") {
3436
+ const summary = this.#summaries.get(item.id) ?? item.summary?.join("\n\n") ?? "";
3437
+ this.#summaries.delete(item.id);
3438
+ this.#reasoning(item.id, summary, endedAt, update, endedAt);
3439
+ return;
3440
+ }
3441
+ const label = itemLabel(item);
3442
+ if (!label) return;
3443
+ const status = itemStatus(item);
3444
+ const detail = finishedDetail(item, label);
3445
+ const step = {
3446
+ id: item.id,
3447
+ label: status === "failed" ? label.running : label.done,
3448
+ status,
3449
+ ...detail ? { detail } : {},
3450
+ startedAt: this.#steps.get(item.id)?.startedAt ?? endedAt,
3451
+ endedAt
3452
+ };
3453
+ this.#steps.set(item.id, step);
3454
+ update.steps.push(step);
3455
+ }
3456
+ #reasoning(id, summary, now, update, endedAt) {
3457
+ const label = reasoningLabel(summary);
3458
+ if (!label) return;
3459
+ const step = {
3460
+ id,
3461
+ label: endedAt ? label.done : label.running,
3462
+ status: endedAt ? "done" : "running",
3463
+ ...label.detail ? { detail: label.detail } : {},
3464
+ startedAt: this.#steps.get(id)?.startedAt ?? now,
3465
+ ...endedAt ? { endedAt } : {}
3466
+ };
3467
+ this.#steps.set(id, step);
3468
+ update.steps.push(step);
3469
+ }
3470
+ #finish(now, update) {
3471
+ for (const draft of this.#drafts.values()) if (draft.text.trim()) update.messages.push({
3472
+ ...draft,
3473
+ streaming: false
3474
+ });
3475
+ this.#drafts.clear();
3476
+ for (const step of this.#steps.values()) {
3477
+ if (step.status !== "running") continue;
3478
+ const skipped = {
3479
+ ...step,
3480
+ status: "skipped",
3481
+ endedAt: now
3482
+ };
3483
+ this.#steps.set(step.id, skipped);
3484
+ update.steps.push(skipped);
3485
+ }
3486
+ this.#summaries.clear();
3487
+ this.#turnId = void 0;
3488
+ }
3489
+ };
3490
+ function isUnauthorized(error) {
3491
+ const info = error.codexErrorInfo;
3492
+ if (info === "unauthorized") return true;
3493
+ if (typeof info !== "object" || info === null) return false;
3494
+ return Object.values(info).some((value) => value?.httpStatusCode === 401);
3495
+ }
3496
+ /** A thread's conversation as Codex stored it, in the shape the overlay shows. */
3497
+ function messagesFromHistory(entries, fallbackTime = (/* @__PURE__ */ new Date()).toISOString()) {
3498
+ const messages = [];
3499
+ let createdAt = fallbackTime;
3500
+ for (const { item, startedAtMs } of entries) {
3501
+ if (startedAtMs) createdAt = iso(startedAtMs);
3502
+ if (item.type === "userMessage") {
3503
+ const text = item.content.flatMap((part) => part.type === "text" && part.text ? [part.text] : []).join("\n\n");
3504
+ if (text.trim()) messages.push({
3505
+ id: item.clientId ?? item.id,
3506
+ role: "user",
3507
+ text,
3508
+ streaming: false,
3509
+ createdAt
3510
+ });
3511
+ } else if (item.type === "agentMessage" && item.text.trim()) messages.push({
3512
+ id: item.id,
3513
+ role: "assistant",
3514
+ text: item.text,
3515
+ streaming: false,
3516
+ createdAt
3517
+ });
3518
+ }
3519
+ return messages;
3520
+ }
3521
+ //#endregion
3522
+ //#region ../provider-codex/src/codex-provider.ts
3523
+ const FULL_ACCESS = {
3524
+ sandbox: "danger-full-access",
3525
+ approvalPolicy: "never"
3526
+ };
3527
+ const DEFAULT_IDLE_CLOSE_MS = 6e5;
3528
+ const DEFAULT_RECHECK_MS = 15e3;
3529
+ const PAGE_SIZE = 200;
3530
+ /** Enough for the inbox; a project's older threads are still in Codex itself. */
3531
+ const LISTED_THREADS = 100;
3532
+ /**
3533
+ * Runs Codex through `codex app-server`, under the user's own install and
3534
+ * login. The daemon hosts one process per project while there's work and Codex
3535
+ * stores the conversations, so threads are Codex threads (`codex resume <id>`
3536
+ * opens one in a terminal, and the desktop app lists them too).
3537
+ */
3538
+ var CodexProvider = class {
3539
+ id = "codex";
3540
+ label = "Codex";
3541
+ #options;
3542
+ #info = {
3543
+ id: "codex",
3544
+ label: "Codex",
3545
+ state: "connecting"
3546
+ };
3547
+ #infoListeners = /* @__PURE__ */ new Set();
3548
+ #workspace;
3549
+ #server;
3550
+ /** The process behind `#server`, known from the moment it starts. */
3551
+ #current;
3552
+ #idleTimer;
3553
+ #recheckTimer;
3554
+ #sessions = /* @__PURE__ */ new Map();
3555
+ #disposed = false;
3556
+ constructor(options) {
3557
+ this.#options = options;
3558
+ }
3559
+ /** Whether Codex is there and signed in. Looks again until it is: both happen outside Tencil. */
3560
+ async start() {
3561
+ clearTimeout(this.#recheckTimer);
3562
+ try {
3563
+ const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3564
+ const { account, requiresOpenaiAuth } = await server.request("account/read", {});
3565
+ if (!account && requiresOpenaiAuth) {
3566
+ this.#signedOut(NOT_SIGNED_IN);
3567
+ return;
3568
+ }
3569
+ this.#setInfo({
3570
+ state: "ready",
3571
+ target: basename(workspace)
3572
+ });
3573
+ this.#log(`Codex ready in ${workspace}`);
3574
+ } catch (error) {
3575
+ this.#setInfo({
3576
+ state: "unavailable",
3577
+ detail: errorMessage$1(error)
3578
+ });
3579
+ this.#recheckLater();
3580
+ }
3581
+ }
3582
+ info() {
3583
+ return this.#info;
3584
+ }
3585
+ onInfoChange(listener) {
3586
+ this.#infoListeners.add(listener);
3587
+ return () => this.#infoListeners.delete(listener);
3588
+ }
3589
+ async listThreads() {
3590
+ const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3591
+ const { data } = await server.request("thread/list", {
3592
+ cwd: workspace,
3593
+ sortKey: "updated_at",
3594
+ limit: LISTED_THREADS
3595
+ });
3596
+ const threads = data.map((thread) => ({
3597
+ id: thread.id,
3598
+ title: thread.name || thread.preview?.split("\n", 1)[0] || "New thread",
3599
+ status: this.#status(thread.id).status,
3600
+ updatedAt: (/* @__PURE__ */ new Date(thread.updatedAt * 1e3)).toISOString(),
3601
+ ...thread.gitInfo?.branch ? { branch: thread.gitInfo.branch } : {},
3602
+ agent: "codex"
3603
+ }));
3604
+ return {
3605
+ project: { name: basename(workspace) },
3606
+ threads
3607
+ };
3608
+ }
3609
+ async listModels() {
3610
+ const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3611
+ const available = await pages((cursor) => server.request("model/list", {
3612
+ cursor,
3613
+ limit: PAGE_SIZE
3614
+ }));
3615
+ const models = available.filter((model) => !model.hidden).map(toModel);
3616
+ const { config } = await server.request("config/read", { cwd: workspace }).catch(() => ({ config: void 0 }));
3617
+ const configured = this.#options.model ?? config?.model ?? void 0;
3618
+ if (configured && !models.some((model) => model.id === configured)) models.unshift(toModel({
3619
+ model: configured,
3620
+ displayName: configured
3621
+ }));
3622
+ return {
3623
+ models,
3624
+ defaultModel: configured ?? available.find((model) => model.isDefault)?.model
3625
+ };
3626
+ }
3627
+ threadUrl() {}
3628
+ async createThread(input) {
3629
+ const [server, workspace, model] = await Promise.all([
3630
+ this.#connect(),
3631
+ this.#workspaceRoot(),
3632
+ this.#modelFor(input.model)
3633
+ ]);
3634
+ const { thread } = await server.request("thread/start", {
3635
+ ...this.#threadSettings(workspace),
3636
+ ...model ? { model } : {}
3637
+ });
3638
+ const session = this.#session(thread.id);
3639
+ session.server = server;
3640
+ session.hydrated = Promise.resolve();
3641
+ await server.request("thread/name/set", {
3642
+ threadId: thread.id,
3643
+ name: input.title
3644
+ }).catch((error) => this.#log(`Couldn't name thread ${thread.id}: ${errorMessage$1(error)}`));
3645
+ await this.#startTurn(session, server, input.text, input.attachments);
3646
+ return { providerThreadId: thread.id };
3647
+ }
3648
+ async sendMessage(input) {
3649
+ const session = this.#session(input.providerThreadId);
3650
+ const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3651
+ if (session.server !== server) {
3652
+ await server.request("thread/resume", {
3653
+ threadId: session.id,
3654
+ excludeTurns: true,
3655
+ ...this.#threadSettings(workspace)
3656
+ });
3657
+ session.server = server;
3658
+ }
3659
+ await this.#startTurn(session, server, input.text, input.attachments);
3660
+ }
3661
+ async interrupt(providerThreadId) {
3662
+ const session = this.#sessions.get(providerThreadId);
3663
+ const turnId = session?.tracker.activeTurn();
3664
+ if (!session?.server || !turnId) return;
3665
+ await session.server.request("turn/interrupt", {
3666
+ threadId: session.id,
3667
+ turnId
3668
+ });
3669
+ }
3670
+ watch(providerThreadId, sink) {
3671
+ const session = this.#session(providerThreadId);
3672
+ session.sink = sink;
3673
+ this.#hydrate(session).then(() => {
3674
+ if (session.sink !== sink) return;
3675
+ if (session.missing) return sink.gone();
3676
+ const messages = [...session.messages.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
3677
+ for (const message of messages) sink.message(message);
3678
+ for (const step of session.tracker.steps()) sink.step?.(step);
3679
+ const status = this.#status(session.id);
3680
+ sink.status(status.status, status.detail);
3681
+ }, (error) => this.#log(`Couldn't load thread ${providerThreadId}: ${errorMessage$1(error)}`));
3682
+ return () => {
3683
+ if (session.sink === sink) session.sink = void 0;
3684
+ };
3685
+ }
3686
+ async dispose() {
3687
+ this.#disposed = true;
3688
+ clearTimeout(this.#recheckTimer);
3689
+ this.#closeServer();
3690
+ this.#sessions.clear();
3691
+ }
3692
+ /** A thread not running here is idle, or ended in an error. */
3693
+ #status(id) {
3694
+ return this.#sessions.get(id)?.tracker.status() ?? { status: "idle" };
3695
+ }
3696
+ #session(id) {
3697
+ let session = this.#sessions.get(id);
3698
+ if (!session) {
3699
+ session = {
3700
+ id,
3701
+ tracker: new TurnTracker(),
3702
+ messages: /* @__PURE__ */ new Map()
3703
+ };
3704
+ this.#sessions.set(id, session);
3705
+ }
3706
+ return session;
3707
+ }
3708
+ /** Load the conversation Codex saved, once. */
3709
+ #hydrate(session) {
3710
+ session.hydrated ??= (async () => {
3711
+ const server = await this.#connect();
3712
+ try {
3713
+ for (const message of messagesFromHistory(await readHistory(server, session.id))) if (!session.messages.has(message.id)) session.messages.set(message.id, message);
3714
+ } catch (error) {
3715
+ if (!isMissingThread(error)) throw error;
3716
+ session.missing = true;
3717
+ }
3718
+ })().catch((error) => {
3719
+ session.hydrated = void 0;
3720
+ throw error;
3721
+ });
3722
+ return session.hydrated;
3723
+ }
3724
+ async #startTurn(session, server, text, attachments) {
3725
+ const clientUserMessageId = randomUUID();
3726
+ this.#emit(session, {
3727
+ id: clientUserMessageId,
3728
+ role: "user",
3729
+ text,
3730
+ streaming: false,
3731
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
3732
+ });
3733
+ session.tracker.setStatus({ status: "working" });
3734
+ session.sink?.status("working");
3735
+ try {
3736
+ const { turn } = await server.request("turn/start", {
3737
+ threadId: session.id,
3738
+ clientUserMessageId,
3739
+ summary: "concise",
3740
+ input: [...attachments.map((attachment) => ({
3741
+ type: "image",
3742
+ url: attachment.dataUrl
3743
+ })), {
3744
+ type: "text",
3745
+ text,
3746
+ text_elements: []
3747
+ }]
3748
+ });
3749
+ session.tracker.noteTurn(turn.id);
3750
+ } catch (error) {
3751
+ const detail = errorMessage$1(error);
3752
+ session.tracker.setStatus({
3753
+ status: "error",
3754
+ detail
3755
+ });
3756
+ session.sink?.status("error", detail);
3757
+ throw error;
3758
+ }
3759
+ }
3760
+ #emit(session, message) {
3761
+ session.messages.set(message.id, message);
3762
+ session.sink?.message(message);
3763
+ }
3764
+ #applyUpdate(session, update) {
3765
+ for (const message of update.messages) this.#emit(session, message);
3766
+ for (const step of update.steps) session.sink?.step?.(step);
3767
+ if (update.status) session.sink?.status(update.status.status, update.status.detail);
3768
+ if (update.unauthorized) this.#signedOut(update.unauthorized);
3769
+ }
3770
+ /** The running server, starting one if needed. Each use keeps it open a while longer. */
3771
+ #connect() {
3772
+ if (this.#disposed) return Promise.reject(/* @__PURE__ */ new Error("Tencil is shutting down"));
3773
+ this.#keepOpen();
3774
+ this.#server ??= this.#startServer().catch((error) => {
3775
+ this.#server = void 0;
3776
+ throw error;
3777
+ });
3778
+ return this.#server;
3779
+ }
3780
+ async #startServer() {
3781
+ const server = new AppServer(appServerSpawner(this.#options)(), {
3782
+ notification: (method, params) => this.#notification(method, params),
3783
+ request: (method, params) => this.#answer(method, params),
3784
+ closed: () => this.#serverClosed(server),
3785
+ log: (message) => this.#log(message)
3786
+ });
3787
+ this.#current = server;
3788
+ try {
3789
+ await server.initialize(this.#options.version ?? "0.0.0");
3790
+ } catch (error) {
3791
+ server.close();
3792
+ throw error;
3793
+ }
3794
+ return server;
3795
+ }
3796
+ #notification(method, params) {
3797
+ const threadId = params?.threadId;
3798
+ if (method === "deprecationNotice" || method === "configWarning") {
3799
+ this.#log(`Codex: ${params.summary ?? method}`);
3800
+ return;
3801
+ }
3802
+ const session = threadId ? this.#sessions.get(threadId) : void 0;
3803
+ if (!session) return;
3804
+ if (method === "thread/closed") {
3805
+ session.server = void 0;
3806
+ return;
3807
+ }
3808
+ const update = session.tracker.apply(method, params);
3809
+ this.#applyUpdate(session, update);
3810
+ if (update.turnEnded) this.#keepOpen();
3811
+ }
3812
+ /**
3813
+ * What Codex asks for during a turn. Nobody is at a terminal to answer, so
3814
+ * whatever gets this far is refused and Codex carries on knowing that.
3815
+ */
3816
+ #answer(method, params) {
3817
+ const { reason, command } = params ?? {};
3818
+ const asked = reason ?? command ?? method;
3819
+ switch (method) {
3820
+ case "item/commandExecution/requestApproval":
3821
+ case "item/fileChange/requestApproval":
3822
+ this.#log(`Refused, nobody is here to approve it: ${asked}`);
3823
+ return { decision: "decline" };
3824
+ case "item/permissions/requestApproval":
3825
+ this.#log(`Refused, nobody is here to approve it: ${asked}`);
3826
+ return {
3827
+ permissions: {},
3828
+ scope: "turn"
3829
+ };
3830
+ case "mcpServer/elicitation/request": return {
3831
+ action: "decline",
3832
+ content: null,
3833
+ _meta: null
3834
+ };
3835
+ case "item/tool/requestUserInput": return { answers: {} };
3836
+ default: throw new RpcError$1(METHOD_NOT_FOUND, `Tencil doesn't handle ${method}`);
3837
+ }
3838
+ }
3839
+ #serverClosed(server) {
3840
+ if (this.#current === server) {
3841
+ this.#current = void 0;
3842
+ this.#server = void 0;
3843
+ clearTimeout(this.#idleTimer);
3844
+ }
3845
+ for (const session of this.#sessions.values()) {
3846
+ if (session.server !== server) continue;
3847
+ session.server = void 0;
3848
+ const update = session.tracker.finish();
3849
+ if (session.tracker.status().status === "working") {
3850
+ update.status = {
3851
+ status: "error",
3852
+ detail: "Codex stopped before the turn finished"
3853
+ };
3854
+ session.tracker.setStatus(update.status);
3855
+ }
3856
+ this.#applyUpdate(session, update);
3857
+ }
3858
+ }
3859
+ /** The process stays while anything uses it, and goes once nothing has for a while. */
3860
+ #keepOpen() {
3861
+ clearTimeout(this.#idleTimer);
3862
+ this.#idleTimer = setTimeout(() => {
3863
+ if ([...this.#sessions.values()].some((session) => session.tracker.status().status === "working")) this.#keepOpen();
3864
+ else this.#closeServer();
3865
+ }, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS);
3866
+ this.#idleTimer.unref?.();
3867
+ }
3868
+ #closeServer() {
3869
+ clearTimeout(this.#idleTimer);
3870
+ const server = this.#server;
3871
+ this.#current = void 0;
3872
+ this.#server = void 0;
3873
+ server?.then((connected) => connected.close(), () => {});
3874
+ }
3875
+ #threadSettings(workspace) {
3876
+ return {
3877
+ cwd: workspace,
3878
+ ...this.#options.permissions ?? FULL_ACCESS
3879
+ };
3880
+ }
3881
+ /** The model a new thread asks for: the pick if Codex still offers it, then `--model`. */
3882
+ async #modelFor(picked) {
3883
+ if (!picked) return this.#options.model;
3884
+ return (await this.listModels().catch(() => void 0))?.models.some((model) => model.id === picked) ? picked : this.#options.model;
3885
+ }
3886
+ /** The repository root, so Codex sees the whole project and its AGENTS.md. */
3887
+ #workspaceRoot() {
3888
+ this.#workspace ??= (async () => {
3889
+ const root = await realpath(this.#options.projectRoot).catch(() => this.#options.projectRoot);
3890
+ return await repositoryRoot$1(root) ?? root;
3891
+ })();
3892
+ return this.#workspace;
3893
+ }
3894
+ /** Signed out: a fresh process reads the login made since, so look again with one. */
3895
+ #signedOut(detail) {
3896
+ this.#setInfo({
3897
+ state: "unauthorized",
3898
+ detail
3899
+ });
3900
+ this.#recheckLater();
3901
+ }
3902
+ #recheckLater() {
3903
+ if (this.#disposed) return;
3904
+ clearTimeout(this.#recheckTimer);
3905
+ this.#recheckTimer = setTimeout(() => {
3906
+ if (![...this.#sessions.values()].some((session) => session.tracker.status().status === "working")) this.#closeServer();
3907
+ this.start();
3908
+ }, this.#options.recheckMs ?? DEFAULT_RECHECK_MS);
3909
+ this.#recheckTimer.unref?.();
3910
+ }
3911
+ #setInfo(next) {
3912
+ const info = {
3913
+ id: this.id,
3914
+ label: this.label,
3915
+ ...next
3916
+ };
3917
+ if (info.state === this.#info.state && info.detail === this.#info.detail && info.target === this.#info.target) return;
3918
+ this.#info = info;
3919
+ for (const listener of this.#infoListeners) listener(info);
3920
+ }
3921
+ #log(message) {
3922
+ this.#options.log?.(message);
3923
+ }
3924
+ };
3925
+ function toModel(model) {
3926
+ return {
3927
+ id: model.model,
3928
+ label: model.displayName,
3929
+ group: "Codex",
3930
+ agent: "codex"
3931
+ };
3932
+ }
3933
+ /**
3934
+ * A thread's items, page by page. Only threads Codex keeps paginated history
3935
+ * for can do that; for others (and threads it doesn't have) it answers "not
3936
+ * supported", and reading the whole thread is what's left.
3937
+ */
3938
+ async function readHistory(server, threadId) {
3939
+ try {
3940
+ return await pages((cursor) => server.request("thread/items/list", {
3941
+ threadId,
3942
+ cursor,
3943
+ limit: PAGE_SIZE
3944
+ }));
3945
+ } catch (error) {
3946
+ if (!(error instanceof RpcError$1 && error.code === -32601)) throw error;
3947
+ }
3948
+ const { thread } = await server.request("thread/read", {
3949
+ threadId,
3950
+ includeTurns: true
3951
+ });
3952
+ return thread.turns.flatMap((turn) => (turn.items ?? []).map((item) => ({
3953
+ item,
3954
+ startedAtMs: turn.startedAt ? turn.startedAt * 1e3 : null
3955
+ })));
3956
+ }
3957
+ /** Every page of a cursor-paged list. */
3958
+ async function pages(fetch) {
3959
+ const all = [];
3960
+ let cursor;
3961
+ do {
3962
+ const page = await fetch(cursor);
3963
+ all.push(...page.data);
3964
+ cursor = page.nextCursor ?? void 0;
3965
+ } while (cursor);
3966
+ return all;
3967
+ }
3968
+ /** Codex only says so in words: `no rollout found for thread id …`, `thread not loaded: …`. */
3969
+ function isMissingThread(error) {
3970
+ return error instanceof RpcError$1 && /no rollout|not found|not loaded/i.test(error.message);
3971
+ }
3972
+ /** The nearest folder at or above `dir` with a `.git` entry, if any. */
3973
+ async function repositoryRoot$1(dir) {
3974
+ for (let current = dir;; current = dirname(current)) {
3975
+ if (await exists$1(join(current, ".git"))) return current;
3976
+ if (dirname(current) === current) return void 0;
3977
+ }
3978
+ }
3979
+ const exists$1 = (path) => access(path).then(() => true, () => false);
3980
+ //#endregion
3981
+ //#region ../provider-codex/src/projects.ts
3982
+ /** Run one thing against a Codex process of its own. */
3983
+ async function withServer(options, use) {
3984
+ const server = new AppServer(appServerSpawner(options)(), {
3985
+ notification: () => {},
3986
+ request: (method) => {
3987
+ throw new Error(`Tencil doesn't handle ${method}`);
3988
+ },
3989
+ closed: () => {},
3990
+ log: () => {}
3991
+ });
3992
+ try {
3993
+ await server.initialize("0.0.0");
3994
+ return await use(server);
3995
+ } finally {
3996
+ server.close();
3997
+ }
3998
+ }
3999
+ /** Folders Codex has threads in that still exist, most recently used first. */
4000
+ async function listCodexProjects(options = {}) {
4001
+ const { data } = await withServer(options, (server) => server.request("thread/list", {
4002
+ sortKey: "updated_at",
4003
+ limit: 100,
4004
+ useStateDbOnly: true
4005
+ }));
4006
+ return [...new Set(data.map((thread) => thread.cwd))].filter((folder) => existsSync(folder)).map((folder) => ({
4007
+ workspaceRoot: folder,
4008
+ title: basename(folder)
4009
+ }));
4010
+ }
4011
+ /** What stops Codex running pins on this machine, in a sentence for setup; nothing if all's well. */
4012
+ async function codexProblem(options = {}) {
4013
+ try {
4014
+ const { account, requiresOpenaiAuth } = await withServer(options, (server) => server.request("account/read", {}));
4015
+ return !account && requiresOpenaiAuth ? NOT_SIGNED_IN : void 0;
4016
+ } catch (error) {
4017
+ return errorMessage$1(error);
4018
+ }
4019
+ }
4020
+ //#endregion
2828
4021
  //#region ../provider-t3code/src/auth.ts
2829
4022
  const DEFAULT_T3_URL = "http://127.0.0.1:3773";
2830
4023
  /** Scopes Tencil needs: read thread state and launch/steer threads. */
@@ -4118,7 +5311,7 @@ function errorMessage(error) {
4118
5311
  }
4119
5312
  //#endregion
4120
5313
  //#region src/version.ts
4121
- const VERSION = "0.9.0";
5314
+ const VERSION = "0.11.0";
4122
5315
  //#endregion
4123
5316
  //#region src/daemon/thread-store.ts
4124
5317
  const StoreFile = z.object({
@@ -4215,6 +5408,7 @@ var FileThreadStore = class {
4215
5408
  const PROVIDERS = [
4216
5409
  "t3code",
4217
5410
  "claude-code",
5411
+ "codex",
4218
5412
  "ensemble"
4219
5413
  ];
4220
5414
  const PROVIDER_OPTIONS = [
@@ -4226,6 +5420,10 @@ const PROVIDER_OPTIONS = [
4226
5420
  id: "claude-code",
4227
5421
  label: "Claude Code"
4228
5422
  },
5423
+ {
5424
+ id: "codex",
5425
+ label: "Codex"
5426
+ },
4229
5427
  {
4230
5428
  id: "ensemble",
4231
5429
  label: "Ensemble"
@@ -4260,7 +5458,7 @@ async function saveProvider(provider, dataDir = defaultDataDir()) {
4260
5458
  }
4261
5459
  /**
4262
5460
  * Which agents this machine has: a paired or running T3 Code, an installed
4263
- * Claude Code, a running Ensemble app.
5461
+ * Claude Code, Codex's CLI or desktop app, a running Ensemble app.
4264
5462
  */
4265
5463
  async function detectAgents(options = {}) {
4266
5464
  const [t3code, claudeCode, ensemble] = await Promise.all([
@@ -4271,12 +5469,13 @@ async function detectAgents(options = {}) {
4271
5469
  return {
4272
5470
  t3code,
4273
5471
  "claude-code": claudeCode,
5472
+ codex: findCodex() !== void 0,
4274
5473
  ensemble
4275
5474
  };
4276
5475
  }
4277
5476
  /**
4278
5477
  * The agent for projects that haven't picked one: the saved choice, else the
4279
- * first agent found (T3 Code, Claude Code, Ensemble), else T3 Code.
5478
+ * first agent found (T3 Code, Claude Code, Codex, Ensemble), else T3 Code.
4280
5479
  */
4281
5480
  async function machineProvider(options = {}) {
4282
5481
  const saved = await savedProvider(options.dataDir);
@@ -4284,6 +5483,7 @@ async function machineProvider(options = {}) {
4284
5483
  const found = await detectAgents(options);
4285
5484
  if (found.t3code) return "t3code";
4286
5485
  if (found["claude-code"]) return "claude-code";
5486
+ if (found.codex) return "codex";
4287
5487
  return found.ensemble ? "ensemble" : "t3code";
4288
5488
  }
4289
5489
  async function hasT3Code(t3Url) {
@@ -4307,6 +5507,56 @@ async function hasClaudeCode() {
4307
5507
  return (await Promise.all(candidates.map((path) => access(path).then(() => true, () => false)))).includes(true);
4308
5508
  }
4309
5509
  //#endregion
5510
+ //#region src/daemon/preferences.ts
5511
+ const PreferencesFile = Preferences.extend({ version: z.literal(1) });
5512
+ function preferencesPath(dataDir = defaultDataDir()) {
5513
+ return join(dataDir, "preferences.json");
5514
+ }
5515
+ /**
5516
+ * The person's overlay preferences (theme, shortcuts), shared by every project
5517
+ * on this machine. One file, next to `settings.json`.
5518
+ */
5519
+ var FilePreferences = class {
5520
+ path;
5521
+ #cached;
5522
+ /** Saves run one after another, so a quick second change can't land first. */
5523
+ #writing = Promise.resolve();
5524
+ constructor(path = preferencesPath()) {
5525
+ this.path = path;
5526
+ }
5527
+ async load() {
5528
+ if (this.#cached) return this.#cached;
5529
+ const raw = await readFile(this.path, "utf8").catch(() => void 0);
5530
+ let parsed;
5531
+ try {
5532
+ parsed = raw === void 0 ? void 0 : PreferencesFile.safeParse(JSON.parse(raw));
5533
+ } catch {}
5534
+ const { version: _, ...preferences } = parsed?.success ? parsed.data : { version: 1 };
5535
+ this.#cached = preferences;
5536
+ return preferences;
5537
+ }
5538
+ /** Merges `changes` into what's saved and returns the result. */
5539
+ async update(changes) {
5540
+ const next = {
5541
+ ...await this.load(),
5542
+ ...changes
5543
+ };
5544
+ this.#cached = next;
5545
+ this.#writing = this.#writing.then(() => this.#write(next)).catch(() => {});
5546
+ await this.#writing;
5547
+ return next;
5548
+ }
5549
+ async #write(preferences) {
5550
+ await mkdir(dirname(this.path), { recursive: true });
5551
+ const temp = `${this.path}.tmp`;
5552
+ await writeFile(temp, `${JSON.stringify({
5553
+ version: 1,
5554
+ ...preferences
5555
+ }, null, 2)}\n`);
5556
+ await rename(temp, this.path);
5557
+ }
5558
+ };
5559
+ //#endregion
4310
5560
  //#region src/daemon/project-settings.ts
4311
5561
  const SettingsFile = z.object({
4312
5562
  version: z.literal(1),
@@ -5083,8 +6333,8 @@ const HOUR_MS = 36e5;
5083
6333
  * update started from the overlay: install it, wait until no thread is
5084
6334
  * running, then hand over to the helper that restarts the daemon on it.
5085
6335
  *
5086
- * It waits rather than carrying threads across: Claude Code runs inside
5087
- * the daemon, so a restart would end its running turns.
6336
+ * It waits rather than carrying threads across: Claude Code and Codex run
6337
+ * inside the daemon, so a restart would end their running turns.
5088
6338
  */
5089
6339
  var Updater = class {
5090
6340
  #options;
@@ -5199,12 +6449,16 @@ var Updater = class {
5199
6449
  const DEFAULT_PORT = 4747;
5200
6450
  /** Screenshots ride along as data URLs. */
5201
6451
  const MAX_PAYLOAD_BYTES = 33554432;
5202
- /**
5203
- * One Tencil daemon per machine. Pages load `/tencil.js` from it; each
5204
- * page's WebSocket is attached to the project it belongs to (worked out from
5205
- * the dev server's port, or picked by the user), and every project gets its
5206
- * own bridge, provider connection and pin store, created on first use.
5207
- */
6452
+ /** The detected project behind a result, also when a pick overrides it. */
6453
+ function automaticPart(found) {
6454
+ if (!found) return void 0;
6455
+ if (found.source.via === "picked") return found.source.detected;
6456
+ return {
6457
+ root: found.root,
6458
+ via: found.source.via,
6459
+ port: found.source.port
6460
+ };
6461
+ }
5208
6462
  async function startDaemon(options = {}) {
5209
6463
  const port = options.port ?? 4747;
5210
6464
  const host = options.host ?? "127.0.0.1";
@@ -5222,10 +6476,18 @@ async function startDaemon(options = {}) {
5222
6476
  exec: options.exec,
5223
6477
  ensembleForPort: (port) => ensembleProjectForPort(port, ensembleOptions)
5224
6478
  });
5225
- const resolveProject = options.resolveProject ?? ((pageUrl, root) => resolver.resolve(pageUrl, root));
6479
+ const detectProject = async (pageUrl, root) => {
6480
+ if (!options.resolveProject) return resolver.detect(pageUrl, root);
6481
+ const found = await options.resolveProject(pageUrl, root);
6482
+ return found ? {
6483
+ root: found,
6484
+ source: { via: "port" }
6485
+ } : void 0;
6486
+ };
5226
6487
  const sessions = /* @__PURE__ */ new Map();
5227
6488
  const overlayPath = resolveOverlayPath();
5228
6489
  let updater;
6490
+ const preferences = new FilePreferences(preferencesPath(dataDir));
5229
6491
  const claudeCodeDir = join(dataDir, "claude-code");
5230
6492
  const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
5231
6493
  const createProvider = options.createProvider ?? ((root, id) => {
@@ -5236,6 +6498,12 @@ async function startDaemon(options = {}) {
5236
6498
  installDir: claudeCodeDir,
5237
6499
  log: providerLog
5238
6500
  });
6501
+ if (id === "codex") return new CodexProvider({
6502
+ ...options.codex,
6503
+ projectRoot: root,
6504
+ version: VERSION,
6505
+ log: providerLog
6506
+ });
5239
6507
  if (id === "ensemble") return new EnsembleProvider({
5240
6508
  projectRoot: root,
5241
6509
  ...ensembleOptions,
@@ -5293,19 +6561,21 @@ async function startDaemon(options = {}) {
5293
6561
  };
5294
6562
  /** Projects any agent knows, offered when a page's project can't be worked out. */
5295
6563
  const choices = async () => {
5296
- const [t3, claude, ensemble] = await Promise.all([
6564
+ const [t3, claude, codex, ensemble] = await Promise.all([
5297
6565
  listT3Projects({
5298
6566
  baseUrl: t3Url,
5299
6567
  token: options.t3?.token ?? process.env.TENCIL_T3_TOKEN,
5300
6568
  credentials: options.t3?.credentials
5301
6569
  }).catch(() => []),
5302
6570
  listClaudeCodeProjects({ installDir: claudeCodeDir }).catch(() => []),
6571
+ listCodexProjects(options.codex).catch(() => []),
5303
6572
  listEnsembleProjects(ensembleOptions).catch(() => [])
5304
6573
  ]);
5305
6574
  const byRoot = /* @__PURE__ */ new Map();
5306
6575
  for (const project of [
5307
6576
  ...t3,
5308
6577
  ...claude,
6578
+ ...codex,
5309
6579
  ...ensemble
5310
6580
  ]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
5311
6581
  root: project.workspaceRoot,
@@ -5313,7 +6583,7 @@ async function startDaemon(options = {}) {
5313
6583
  });
5314
6584
  return [...byRoot.values()];
5315
6585
  };
5316
- const noChoicesHint = "No projects found. Open this page's project in T3 Code or Ensemble, or run claude in it once.";
6586
+ const noChoicesHint = "No projects found. Open this page's project in T3 Code or Ensemble, or run claude or codex in it once.";
5317
6587
  const settled = async () => (await Promise.allSettled(sessions.values())).filter((r) => r.status === "fulfilled").map((r) => r.value);
5318
6588
  let statuses = [];
5319
6589
  const refreshStatuses = async () => {
@@ -5381,7 +6651,13 @@ async function startDaemon(options = {}) {
5381
6651
  let current;
5382
6652
  let detach;
5383
6653
  let pageUrl = "";
6654
+ /** What detection found for this page, to switch from and back to. */
6655
+ let detected;
5384
6656
  let queue = Promise.resolve();
6657
+ preferences.load().then((saved) => client.send({
6658
+ type: "preferences",
6659
+ preferences: saved
6660
+ }));
5385
6661
  const attach = async (root, hello) => {
5386
6662
  detach?.();
5387
6663
  if (current) current.clients--;
@@ -5395,8 +6671,15 @@ async function startDaemon(options = {}) {
5395
6671
  if (message.type === "hello") {
5396
6672
  pageUrl = message.pageUrl ?? "";
5397
6673
  const claimed = typeof message.root === "string" ? message.root : void 0;
5398
- const root = await resolveProject(pageUrl, claimed).catch(() => void 0);
5399
- if (root) return attach(root, raw);
6674
+ const found = await detectProject(pageUrl, claimed).catch(() => void 0);
6675
+ detected = automaticPart(found);
6676
+ if (found) {
6677
+ await attach(found.root, raw);
6678
+ return client.send({
6679
+ type: "project.source",
6680
+ source: found.source
6681
+ });
6682
+ }
5400
6683
  return client.send({
5401
6684
  type: "project.unknown",
5402
6685
  pageUrl,
@@ -5409,14 +6692,42 @@ async function startDaemon(options = {}) {
5409
6692
  updater.update();
5410
6693
  return;
5411
6694
  }
6695
+ if (message.type === "preferences.update") {
6696
+ const changes = Preferences.parse(raw.preferences);
6697
+ const saved = await preferences.update(changes);
6698
+ const update = JSON.stringify({
6699
+ type: "preferences",
6700
+ preferences: saved
6701
+ });
6702
+ for (const other of wss.clients) if (other.readyState === WebSocket$1.OPEN) other.send(update);
6703
+ return;
6704
+ }
5412
6705
  if (message.type === "project.select" && message.root) {
5413
- await resolver.remember(pageUrl, message.root);
5414
- return attach(message.root, {
6706
+ const root = message.root;
6707
+ const auto = detected;
6708
+ if (auto) await resolver.pick(pageUrl, auto.root, root);
6709
+ else await resolver.remember(pageUrl, root);
6710
+ await attach(root, {
5415
6711
  type: "hello",
5416
6712
  protocol: 1,
5417
6713
  pageUrl
5418
6714
  });
6715
+ const source = !auto ? { via: "picked" } : projectKey(root) === auto.root ? {
6716
+ via: auto.via,
6717
+ port: auto.port
6718
+ } : {
6719
+ via: "picked",
6720
+ detected: auto
6721
+ };
6722
+ return client.send({
6723
+ type: "project.source",
6724
+ source
6725
+ });
5419
6726
  }
6727
+ if (message.type === "project.choices") return client.send({
6728
+ type: "project.choices",
6729
+ choices: await choices()
6730
+ });
5420
6731
  if (!current) return client.send({
5421
6732
  type: "error",
5422
6733
  message: "No project selected yet"
@@ -5526,4 +6837,4 @@ function resolveOverlayPath() {
5526
6837
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
5527
6838
  }
5528
6839
  //#endregion
5529
- export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E, EnsembleClient as F, Bridge as I, renderPrompt as L, ProjectResolver as M, projectRoot as N, exchangePairingCredential as O, EnsembleCredentialStore as P, stripContext as R, defaultDataDir as S, CredentialStore as T, detectAgents as _, readPlan as a, savedProvider as b, runtimeDir as c, uninstallService as d, startInBackground as f, PROVIDERS as g, updateNotice as h, finishUpdate as i, loadAgentSdk as j, parsePairingInput as k, isServiceInstalled as l, isNewerThanThis as m, probeDaemon as n, enableAutostart as o, stopDaemon as p, startDaemon as r, ensureDaemon as s, DEFAULT_PORT as t, stopService as u, providerLabel as v, VERSION as w, FileThreadStore as x, saveProvider as y };
6840
+ export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E, EnsembleCredentialStore as F, EnsembleClient as I, Bridge as L, loadAgentSdk as M, ProjectResolver as N, exchangePairingCredential as O, projectRoot as P, renderPrompt as R, defaultDataDir as S, CredentialStore as T, detectAgents as _, readPlan as a, savedProvider as b, runtimeDir as c, uninstallService as d, startInBackground as f, PROVIDERS as g, updateNotice as h, finishUpdate as i, codexProblem as j, parsePairingInput as k, isServiceInstalled as l, isNewerThanThis as m, probeDaemon as n, enableAutostart as o, stopDaemon as p, startDaemon as r, ensureDaemon as s, DEFAULT_PORT as t, stopService as u, providerLabel as v, VERSION as w, FileThreadStore as x, saveProvider as y, stripContext as z };