tencil 0.10.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. */
@@ -1476,7 +1477,7 @@ var EnsembleClient = class {
1476
1477
  throw response.status === 401 ? new EnsembleUnauthorizedError(reason) : new EnsembleHttpError(response.status, reason);
1477
1478
  }
1478
1479
  };
1479
- function errorMessage$2(error) {
1480
+ function errorMessage$3(error) {
1480
1481
  return error instanceof Error ? error.message : String(error);
1481
1482
  }
1482
1483
  function threadPath(threadId) {
@@ -1729,7 +1730,7 @@ var ThreadFeed = class {
1729
1730
  type: "archived",
1730
1731
  threadId: this.threadId
1731
1732
  });
1732
- this.options.log?.(`Reconnecting to Ensemble's feed: ${errorMessage$2(error)}`);
1733
+ this.options.log?.(`Reconnecting to Ensemble's feed: ${errorMessage$3(error)}`);
1733
1734
  }
1734
1735
  await setTimeout$1(delayMs, void 0, {
1735
1736
  signal,
@@ -1994,7 +1995,7 @@ var EnsembleProvider = class {
1994
1995
  state: "unavailable",
1995
1996
  detail: "This Ensemble thread is closed. Choose an open one."
1996
1997
  });
1997
- this.#retryLater(`Ensemble didn't answer: ${errorMessage$2(error)}`);
1998
+ this.#retryLater(`Ensemble didn't answer: ${errorMessage$3(error)}`);
1998
1999
  }
1999
2000
  }
2000
2001
  async #pair() {
@@ -2009,7 +2010,7 @@ var EnsembleProvider = class {
2009
2010
  this.#setInfo({
2010
2011
  state: "unauthorized",
2011
2012
  canPair: true,
2012
- detail: errorMessage$2(error)
2013
+ detail: errorMessage$3(error)
2013
2014
  });
2014
2015
  throw error;
2015
2016
  }
@@ -2216,7 +2217,7 @@ var ProjectResolver = class {
2216
2217
  }
2217
2218
  /** Working directory of the compose project whose container publishes `port`. */
2218
2219
  async #composeFolder(port) {
2219
- return firstLine(await this.#exec("docker", [
2220
+ return firstLine$1(await this.#exec("docker", [
2220
2221
  "ps",
2221
2222
  "--filter",
2222
2223
  `publish=${port}`,
@@ -2319,7 +2320,7 @@ function isDockerForwarder(commandLine) {
2319
2320
  function projectFromCommandLine(commandLine) {
2320
2321
  return commandLine.match(/(?:^|[\s"'])((?:[A-Za-z]:)?[\\/][^\s"']*?)[\\/]node_modules[\\/]/)?.[1];
2321
2322
  }
2322
- function firstLine(output) {
2323
+ function firstLine$1(output) {
2323
2324
  return output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
2324
2325
  }
2325
2326
  function safeOrigin(pageUrl) {
@@ -2461,7 +2462,7 @@ async function installAgentSdk(installDir) {
2461
2462
  * the same id the transcript on disk carries, so a replay lines up with them.
2462
2463
  * Subagent output and tool results stay out: the overlay shows the conversation.
2463
2464
  */
2464
- var TurnTracker = class {
2465
+ var TurnTracker$1 = class {
2465
2466
  #drafts = /* @__PURE__ */ new Map();
2466
2467
  #current;
2467
2468
  #status = { status: "idle" };
@@ -2634,7 +2635,7 @@ function toMessage(draft) {
2634
2635
  }
2635
2636
  //#endregion
2636
2637
  //#region ../provider-claude-code/src/claude-code-provider.ts
2637
- const DEFAULT_IDLE_CLOSE_MS = 6e5;
2638
+ const DEFAULT_IDLE_CLOSE_MS$1 = 6e5;
2638
2639
  /**
2639
2640
  * Runs Claude Code through the Agent SDK. Unlike T3 Code there is no server
2640
2641
  * holding the conversation: the daemon hosts one Claude Code process per
@@ -2671,7 +2672,7 @@ var ClaudeCodeProvider = class {
2671
2672
  this.#sdk = void 0;
2672
2673
  this.#setInfo({
2673
2674
  state: "unavailable",
2674
- detail: errorMessage$1(error)
2675
+ detail: errorMessage$2(error)
2675
2676
  });
2676
2677
  }
2677
2678
  }
@@ -2732,7 +2733,7 @@ var ClaudeCodeProvider = class {
2732
2733
  for (const message of messages) sink.message(message);
2733
2734
  const status = this.#status(session.id);
2734
2735
  sink.status(status.status, status.detail);
2735
- }, (error) => this.#log(`Couldn't load session ${providerThreadId}: ${errorMessage$1(error)}`));
2736
+ }, (error) => this.#log(`Couldn't load session ${providerThreadId}: ${errorMessage$2(error)}`));
2736
2737
  return () => {
2737
2738
  if (session.sink === sink) session.sink = void 0;
2738
2739
  };
@@ -2754,7 +2755,7 @@ var ClaudeCodeProvider = class {
2754
2755
  if (!session) {
2755
2756
  session = {
2756
2757
  id,
2757
- tracker: new TurnTracker(),
2758
+ tracker: new TurnTracker$1(),
2758
2759
  messages: /* @__PURE__ */ new Map()
2759
2760
  };
2760
2761
  this.#sessions.set(id, session);
@@ -2829,7 +2830,7 @@ var ClaudeCodeProvider = class {
2829
2830
  if (update.turnEnded) this.#scheduleIdleClose(session, run);
2830
2831
  }
2831
2832
  } catch (error) {
2832
- failure = errorMessage$1(error);
2833
+ failure = errorMessage$2(error);
2833
2834
  }
2834
2835
  if (session.run !== run) return;
2835
2836
  session.run = void 0;
@@ -2879,7 +2880,7 @@ var ClaudeCodeProvider = class {
2879
2880
  if (session.tracker.status().status === "working") return;
2880
2881
  run.idleTimer = setTimeout(() => {
2881
2882
  if (session.run === run) this.#close(session);
2882
- }, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS);
2883
+ }, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS$1);
2883
2884
  run.idleTimer.unref?.();
2884
2885
  }
2885
2886
  #close(session) {
@@ -2908,7 +2909,7 @@ var ClaudeCodeProvider = class {
2908
2909
  #workspaceRoot() {
2909
2910
  this.#workspace ??= (async () => {
2910
2911
  const root = await realpath(this.#options.projectRoot).catch(() => this.#options.projectRoot);
2911
- return await repositoryRoot$1(root) ?? root;
2912
+ return await repositoryRoot$2(root) ?? root;
2912
2913
  })();
2913
2914
  return this.#workspace;
2914
2915
  }
@@ -2938,14 +2939,14 @@ function imageBlock(attachment) {
2938
2939
  };
2939
2940
  }
2940
2941
  /** The nearest folder at or above `dir` with a `.git` entry, if any. */
2941
- async function repositoryRoot$1(dir) {
2942
+ async function repositoryRoot$2(dir) {
2942
2943
  for (let current = dir;; current = dirname(current)) {
2943
- if (await exists$1(join(current, ".git"))) return current;
2944
+ if (await exists$2(join(current, ".git"))) return current;
2944
2945
  if (dirname(current) === current) return void 0;
2945
2946
  }
2946
2947
  }
2947
- const exists$1 = (path) => access(path).then(() => true, () => false);
2948
- function errorMessage$1(error) {
2948
+ const exists$2 = (path) => access(path).then(() => true, () => false);
2949
+ function errorMessage$2(error) {
2949
2950
  return error instanceof Error ? error.message : String(error);
2950
2951
  }
2951
2952
  //#endregion
@@ -2966,6 +2967,1057 @@ async function listClaudeCodeProjects(options) {
2966
2967
  return projects;
2967
2968
  }
2968
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
2969
4021
  //#region ../provider-t3code/src/auth.ts
2970
4022
  const DEFAULT_T3_URL = "http://127.0.0.1:3773";
2971
4023
  /** Scopes Tencil needs: read thread state and launch/steer threads. */
@@ -4259,7 +5311,7 @@ function errorMessage(error) {
4259
5311
  }
4260
5312
  //#endregion
4261
5313
  //#region src/version.ts
4262
- const VERSION = "0.10.0";
5314
+ const VERSION = "0.11.0";
4263
5315
  //#endregion
4264
5316
  //#region src/daemon/thread-store.ts
4265
5317
  const StoreFile = z.object({
@@ -4356,6 +5408,7 @@ var FileThreadStore = class {
4356
5408
  const PROVIDERS = [
4357
5409
  "t3code",
4358
5410
  "claude-code",
5411
+ "codex",
4359
5412
  "ensemble"
4360
5413
  ];
4361
5414
  const PROVIDER_OPTIONS = [
@@ -4367,6 +5420,10 @@ const PROVIDER_OPTIONS = [
4367
5420
  id: "claude-code",
4368
5421
  label: "Claude Code"
4369
5422
  },
5423
+ {
5424
+ id: "codex",
5425
+ label: "Codex"
5426
+ },
4370
5427
  {
4371
5428
  id: "ensemble",
4372
5429
  label: "Ensemble"
@@ -4401,7 +5458,7 @@ async function saveProvider(provider, dataDir = defaultDataDir()) {
4401
5458
  }
4402
5459
  /**
4403
5460
  * Which agents this machine has: a paired or running T3 Code, an installed
4404
- * Claude Code, a running Ensemble app.
5461
+ * Claude Code, Codex's CLI or desktop app, a running Ensemble app.
4405
5462
  */
4406
5463
  async function detectAgents(options = {}) {
4407
5464
  const [t3code, claudeCode, ensemble] = await Promise.all([
@@ -4412,12 +5469,13 @@ async function detectAgents(options = {}) {
4412
5469
  return {
4413
5470
  t3code,
4414
5471
  "claude-code": claudeCode,
5472
+ codex: findCodex() !== void 0,
4415
5473
  ensemble
4416
5474
  };
4417
5475
  }
4418
5476
  /**
4419
5477
  * The agent for projects that haven't picked one: the saved choice, else the
4420
- * first agent found (T3 Code, Claude Code, Ensemble), else T3 Code.
5478
+ * first agent found (T3 Code, Claude Code, Codex, Ensemble), else T3 Code.
4421
5479
  */
4422
5480
  async function machineProvider(options = {}) {
4423
5481
  const saved = await savedProvider(options.dataDir);
@@ -4425,6 +5483,7 @@ async function machineProvider(options = {}) {
4425
5483
  const found = await detectAgents(options);
4426
5484
  if (found.t3code) return "t3code";
4427
5485
  if (found["claude-code"]) return "claude-code";
5486
+ if (found.codex) return "codex";
4428
5487
  return found.ensemble ? "ensemble" : "t3code";
4429
5488
  }
4430
5489
  async function hasT3Code(t3Url) {
@@ -5274,8 +6333,8 @@ const HOUR_MS = 36e5;
5274
6333
  * update started from the overlay: install it, wait until no thread is
5275
6334
  * running, then hand over to the helper that restarts the daemon on it.
5276
6335
  *
5277
- * It waits rather than carrying threads across: Claude Code runs inside
5278
- * 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.
5279
6338
  */
5280
6339
  var Updater = class {
5281
6340
  #options;
@@ -5439,6 +6498,12 @@ async function startDaemon(options = {}) {
5439
6498
  installDir: claudeCodeDir,
5440
6499
  log: providerLog
5441
6500
  });
6501
+ if (id === "codex") return new CodexProvider({
6502
+ ...options.codex,
6503
+ projectRoot: root,
6504
+ version: VERSION,
6505
+ log: providerLog
6506
+ });
5442
6507
  if (id === "ensemble") return new EnsembleProvider({
5443
6508
  projectRoot: root,
5444
6509
  ...ensembleOptions,
@@ -5496,19 +6561,21 @@ async function startDaemon(options = {}) {
5496
6561
  };
5497
6562
  /** Projects any agent knows, offered when a page's project can't be worked out. */
5498
6563
  const choices = async () => {
5499
- const [t3, claude, ensemble] = await Promise.all([
6564
+ const [t3, claude, codex, ensemble] = await Promise.all([
5500
6565
  listT3Projects({
5501
6566
  baseUrl: t3Url,
5502
6567
  token: options.t3?.token ?? process.env.TENCIL_T3_TOKEN,
5503
6568
  credentials: options.t3?.credentials
5504
6569
  }).catch(() => []),
5505
6570
  listClaudeCodeProjects({ installDir: claudeCodeDir }).catch(() => []),
6571
+ listCodexProjects(options.codex).catch(() => []),
5506
6572
  listEnsembleProjects(ensembleOptions).catch(() => [])
5507
6573
  ]);
5508
6574
  const byRoot = /* @__PURE__ */ new Map();
5509
6575
  for (const project of [
5510
6576
  ...t3,
5511
6577
  ...claude,
6578
+ ...codex,
5512
6579
  ...ensemble
5513
6580
  ]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
5514
6581
  root: project.workspaceRoot,
@@ -5516,7 +6583,7 @@ async function startDaemon(options = {}) {
5516
6583
  });
5517
6584
  return [...byRoot.values()];
5518
6585
  };
5519
- 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.";
5520
6587
  const settled = async () => (await Promise.allSettled(sessions.values())).filter((r) => r.status === "fulfilled").map((r) => r.value);
5521
6588
  let statuses = [];
5522
6589
  const refreshStatuses = async () => {
@@ -5770,4 +6837,4 @@ function resolveOverlayPath() {
5770
6837
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
5771
6838
  }
5772
6839
  //#endregion
5773
- 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 };