tencil 0.8.0 → 0.9.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.
@@ -4,10 +4,11 @@ import { existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writ
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
6
  import { promisify } from "node:util";
7
- import { createServer } from "node:http";
8
- import { fileURLToPath, pathToFileURL } from "node:url";
9
7
  import { createHash, randomUUID } from "node:crypto";
10
8
  import { homedir } from "node:os";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
+ import { createServer } from "node:http";
11
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
12
  import { WebSocket as WebSocket$1, WebSocketServer } from "ws";
12
13
  //#region ../protocol/src/context.ts
13
14
  /** A resolved source location for the element, usually from React's owner stack. */
@@ -341,7 +342,9 @@ const Thread = z.object({
341
342
  id: z.string(),
342
343
  threadId: z.string().optional(),
343
344
  /** Deep link into the provider UI, when it has one. */
344
- url: z.string().optional()
345
+ url: z.string().optional(),
346
+ /** Started for these pins: archived once they're all resolved (`Provider.archive`). */
347
+ archivable: z.boolean().optional()
345
348
  }),
346
349
  /** Tencil Cloud only: the run's commit, pull request and preview. */
347
350
  delivery: Delivery.optional(),
@@ -538,7 +541,7 @@ var Bridge = class {
538
541
  type: "settings",
539
542
  settings: this.#settings()
540
543
  }));
541
- for (const thread of options.store.list()) if (thread.provider.threadId && options.providers.has(thread.provider.id)) this.#watch(thread.provider.id, thread.provider.threadId);
544
+ for (const thread of options.store.list()) if (thread.provider.threadId && options.providers.has(thread.provider.id) && !this.#archived(thread.provider)) this.#watch(thread.provider.id, thread.provider.threadId);
542
545
  }
543
546
  connect(client) {
544
547
  this.#clients.add(client);
@@ -633,10 +636,7 @@ var Bridge = class {
633
636
  return;
634
637
  }
635
638
  case "thread.resolve":
636
- this.#update(message.threadId, (thread) => ({
637
- ...thread,
638
- resolved: message.resolved
639
- }));
639
+ await this.#resolve(message.threadId, message.resolved);
640
640
  return;
641
641
  case "thread.move":
642
642
  this.#update(message.threadId, (thread) => ({
@@ -645,13 +645,15 @@ var Bridge = class {
645
645
  }));
646
646
  return;
647
647
  case "thread.delete": {
648
- const provider = this.#options.store.get(message.threadId)?.provider;
648
+ const thread = this.#options.store.get(message.threadId);
649
649
  this.#draftAttachments.delete(message.threadId);
650
650
  if (this.#options.store.delete(message.threadId)) this.#broadcast({
651
651
  type: "thread.removed",
652
652
  threadId: message.threadId
653
653
  });
654
- if (provider?.threadId) this.#release(provider.id, provider.threadId);
654
+ if (!thread?.provider.threadId) return;
655
+ if (!thread.resolved && this.#options.providers.has(thread.provider.id) && this.#archived(thread.provider)) await this.#archive(thread);
656
+ this.#release(thread.provider.id, thread.provider.threadId);
655
657
  return;
656
658
  }
657
659
  case "update.start": throw new Error("Tencil can't update itself here");
@@ -711,7 +713,8 @@ var Bridge = class {
711
713
  provider: {
712
714
  id: provider.id,
713
715
  threadId: created.providerThreadId,
714
- url: created.url
716
+ url: created.url,
717
+ archivable: created.archivable
715
718
  }
716
719
  }));
717
720
  this.#watch(provider.id, created.providerThreadId);
@@ -798,7 +801,8 @@ var Bridge = class {
798
801
  provider: {
799
802
  id: provider.id,
800
803
  threadId: created.providerThreadId,
801
- url: created.url
804
+ url: created.url,
805
+ archivable: created.archivable
802
806
  }
803
807
  }));
804
808
  }
@@ -834,7 +838,8 @@ var Bridge = class {
834
838
  provider: {
835
839
  id: provider.id,
836
840
  threadId: providerThreadId,
837
- url: provider.threadUrl(providerThreadId)
841
+ url: provider.threadUrl(providerThreadId),
842
+ archivable: sibling?.provider.archivable
838
843
  },
839
844
  createdAt: now,
840
845
  updatedAt: now
@@ -883,7 +888,8 @@ var Bridge = class {
883
888
  provider: {
884
889
  id: provider.id,
885
890
  threadId: message.providerThreadId,
886
- url: provider.threadUrl(message.providerThreadId)
891
+ url: provider.threadUrl(message.providerThreadId),
892
+ archivable: sibling?.provider.archivable
887
893
  },
888
894
  createdAt: now,
889
895
  updatedAt: now
@@ -895,9 +901,9 @@ var Bridge = class {
895
901
  async #reply(message) {
896
902
  const thread = this.#require(message.threadId);
897
903
  if (!thread.provider.threadId) throw new Error("This pin has no agent thread yet");
904
+ await this.#resolve(thread.id, false);
898
905
  this.#update(thread.id, (current) => ({
899
906
  ...current,
900
- resolved: false,
901
907
  status: "working",
902
908
  statusDetail: void 0,
903
909
  steps: void 0,
@@ -910,6 +916,43 @@ var Bridge = class {
910
916
  });
911
917
  }
912
918
  /**
919
+ * A thread the provider started for its pins is archived once every pin on it is
920
+ * resolved, and reopened when one is reopened. It isn't watched while archived.
921
+ */
922
+ async #resolve(threadId, resolved) {
923
+ const thread = this.#require(threadId);
924
+ if (thread.resolved === resolved) return;
925
+ const { id: providerId, threadId: providerThreadId, archivable } = thread.provider;
926
+ const others = providerThreadId ? this.#pinsFor(providerId, providerThreadId).filter((pin) => pin.id !== threadId) : [];
927
+ if (archivable && providerThreadId && others.every((pin) => pin.resolved)) {
928
+ if (resolved) await this.#archive(thread);
929
+ else {
930
+ await this.#providerOf(thread).reopen?.(providerThreadId);
931
+ this.#watch(providerId, providerThreadId, true);
932
+ }
933
+ }
934
+ this.#update(threadId, (current) => ({
935
+ ...current,
936
+ resolved
937
+ }));
938
+ }
939
+ /** Archive the pin's provider thread, which its other pins, if any, are done with. */
940
+ async #archive(thread) {
941
+ const { id: providerId, threadId: providerThreadId } = thread.provider;
942
+ if (!providerThreadId) return;
943
+ this.#unwatch(providerId, providerThreadId);
944
+ try {
945
+ await this.#providerOf(thread).archive?.(providerThreadId);
946
+ } catch (error) {
947
+ if (this.#pinsFor(providerId, providerThreadId).length > 0) this.#watch(providerId, providerThreadId);
948
+ throw error;
949
+ }
950
+ }
951
+ /** Whether the provider thread is archived: started for its pins, which are all resolved. */
952
+ #archived(provider) {
953
+ return provider.archivable === true && provider.threadId !== void 0 && this.#pinsFor(provider.id, provider.threadId).every((pin) => pin.resolved);
954
+ }
955
+ /**
913
956
  * Subscribe once per provider thread and fan updates out to every bound pin.
914
957
  * `replay` re-subscribes an existing watch so a newly bound pin receives the
915
958
  * provider's snapshot too.
@@ -943,7 +986,9 @@ var Bridge = class {
943
986
  this.#watches.set(key, unwatch);
944
987
  }
945
988
  #release(providerId, providerThreadId) {
946
- if (this.#pinsFor(providerId, providerThreadId).length > 0) return;
989
+ if (this.#pinsFor(providerId, providerThreadId).length === 0) this.#unwatch(providerId, providerThreadId);
990
+ }
991
+ #unwatch(providerId, providerThreadId) {
947
992
  const key = watchKey(providerId, providerThreadId);
948
993
  this.#watches.get(key)?.();
949
994
  this.#watches.delete(key);
@@ -1210,6 +1255,772 @@ function settleInterrupted(thread) {
1210
1255
  statusDetail: "Bridge stopped before the thread was created"
1211
1256
  };
1212
1257
  }
1258
+ /** Where Ensemble's public API listens; `TENCIL_ENSEMBLE_URL` points elsewhere. */
1259
+ function ensembleUrl() {
1260
+ return process.env.TENCIL_ENSEMBLE_URL ?? "http://127.0.0.1:7434";
1261
+ }
1262
+ var EnsembleHttpError = class extends Error {
1263
+ status;
1264
+ constructor(status, reason) {
1265
+ super(`Ensemble returned ${status}: ${reason}`);
1266
+ this.status = status;
1267
+ this.name = "EnsembleHttpError";
1268
+ }
1269
+ };
1270
+ /** The token is missing, or the user removed Tencil in Ensemble › Settings › Ensemble API. */
1271
+ var EnsembleUnauthorizedError = class extends EnsembleHttpError {
1272
+ constructor(reason) {
1273
+ super(401, reason);
1274
+ this.name = "EnsembleUnauthorizedError";
1275
+ }
1276
+ };
1277
+ /** Ensemble's public local API. Every write carries an idempotency key. */
1278
+ var EnsembleClient = class {
1279
+ baseUrl;
1280
+ #token;
1281
+ #timeoutMs;
1282
+ constructor(options = {}) {
1283
+ this.baseUrl = new URL(options.baseUrl ?? ensembleUrl()).origin;
1284
+ this.#token = options.token;
1285
+ this.#timeoutMs = options.timeoutMs ?? 1e4;
1286
+ }
1287
+ /** Whether the Ensemble app is running; this needs no token. */
1288
+ async isRunning() {
1289
+ try {
1290
+ const about = await this.#request("GET", "", {
1291
+ auth: false,
1292
+ timeoutMs: 1500
1293
+ });
1294
+ return about.name === "ensemble" && about.api === 1;
1295
+ } catch {
1296
+ return false;
1297
+ }
1298
+ }
1299
+ /** Ask the user to allow Tencil. Ensemble keeps the request open while it asks, up to 2 minutes. */
1300
+ async connect() {
1301
+ const { token } = await this.#request("POST", "connect", {
1302
+ body: {
1303
+ name: "Tencil",
1304
+ access: "work"
1305
+ },
1306
+ auth: false,
1307
+ timeoutMs: 125e3
1308
+ });
1309
+ return token;
1310
+ }
1311
+ projects() {
1312
+ return this.#request("GET", "projects");
1313
+ }
1314
+ /**
1315
+ * Open threads; with `port`, only the one whose app listens on that port of this Mac,
1316
+ * with `project`, only that project's.
1317
+ */
1318
+ threads(filter = {}) {
1319
+ const query = new URLSearchParams();
1320
+ if (filter.port !== void 0) query.set("port", String(filter.port));
1321
+ if (filter.project !== void 0) query.set("project", filter.project);
1322
+ return this.#request("GET", query.size ? `threads?${query}` : "threads");
1323
+ }
1324
+ /** A new thread in `projectId`, on its own branch; its first chat runs `prompt`. */
1325
+ createThread(thread) {
1326
+ return this.#request("POST", "threads", { body: thread });
1327
+ }
1328
+ thread(threadId) {
1329
+ return this.#request("GET", threadPath(threadId));
1330
+ }
1331
+ /** Saves the thread's work and conversation, and frees its machine. */
1332
+ archiveThread(threadId) {
1333
+ return this.#request("POST", `${threadPath(threadId)}/archive`, { body: {} });
1334
+ }
1335
+ /** Brings an archived thread back on a new machine with its saved work. */
1336
+ reopenThread(threadId) {
1337
+ return this.#request("POST", `${threadPath(threadId)}/reopen`, { body: {} });
1338
+ }
1339
+ createChat(threadId, chat) {
1340
+ return this.#request("POST", `${threadPath(threadId)}/chats`, { body: chat });
1341
+ }
1342
+ /** Queues behind a running turn. */
1343
+ sendMessage(threadId, chatId, message) {
1344
+ return this.#request("POST", `${chatPath(threadId, chatId)}/messages`, { body: message });
1345
+ }
1346
+ stop(threadId, chatId) {
1347
+ return this.#request("POST", `${chatPath(threadId, chatId)}/stop`, { body: {} });
1348
+ }
1349
+ /**
1350
+ * A thread's events, every chat included, until the feed fails. Without `after` it
1351
+ * starts with the whole state. Ensemble pings every 15 s, so a feed silent for
1352
+ * `silenceMs` counts as dropped.
1353
+ */
1354
+ async *feed(threadId, options) {
1355
+ const silenceMs = options.silenceMs ?? 45e3;
1356
+ const silent = new AbortController();
1357
+ let timer = setTimeout(() => silent.abort(), silenceMs);
1358
+ const heard = () => {
1359
+ clearTimeout(timer);
1360
+ timer = setTimeout(() => silent.abort(), silenceMs);
1361
+ };
1362
+ try {
1363
+ const response = await this.#fetch("GET", `feed?thread=${encodeURIComponent(threadId)}`, {
1364
+ headers: {
1365
+ Accept: "text/event-stream",
1366
+ ...options.after ? { "Last-Event-ID": options.after } : {}
1367
+ },
1368
+ signal: AbortSignal.any([options.signal, silent.signal])
1369
+ });
1370
+ if (!response.body) throw new Error("Ensemble sent an empty feed");
1371
+ for await (const message of serverSentEvents(response.body, heard)) {
1372
+ const data = JSON.parse(message.data);
1373
+ const type = data.type ?? message.event;
1374
+ if (type === "error") throw new Error(`Ensemble ended the feed: ${data.error}`);
1375
+ yield {
1376
+ id: message.id,
1377
+ event: {
1378
+ ...data,
1379
+ type
1380
+ }
1381
+ };
1382
+ }
1383
+ throw new Error("Ensemble closed the feed");
1384
+ } finally {
1385
+ clearTimeout(timer);
1386
+ }
1387
+ }
1388
+ async #request(method, path, options = {}) {
1389
+ const response = await this.#fetch(method, path, {
1390
+ auth: options.auth,
1391
+ headers: options.body === void 0 ? {} : { "Content-Type": "application/json" },
1392
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
1393
+ signal: AbortSignal.timeout(options.timeoutMs ?? this.#timeoutMs)
1394
+ });
1395
+ if (response.status === 204) return void 0;
1396
+ return await response.json();
1397
+ }
1398
+ async #fetch(method, path, init) {
1399
+ const response = await fetch(`${this.baseUrl}/v1${path ? `/${path}` : ""}`, {
1400
+ method,
1401
+ headers: {
1402
+ ...init.headers,
1403
+ ...init.auth === false ? {} : { Authorization: `Bearer ${this.#token ?? ""}` },
1404
+ ...method === "POST" ? { "Idempotency-Key": randomUUID() } : {}
1405
+ },
1406
+ body: init.body,
1407
+ signal: init.signal
1408
+ });
1409
+ if (response.ok) return response;
1410
+ const { error } = await response.json().catch(() => ({}));
1411
+ const reason = error ?? response.statusText;
1412
+ throw response.status === 401 ? new EnsembleUnauthorizedError(reason) : new EnsembleHttpError(response.status, reason);
1413
+ }
1414
+ };
1415
+ function errorMessage$2(error) {
1416
+ return error instanceof Error ? error.message : String(error);
1417
+ }
1418
+ function threadPath(threadId) {
1419
+ return `threads/${encodeURIComponent(threadId)}`;
1420
+ }
1421
+ function chatPath(threadId, chatId) {
1422
+ return `${threadPath(threadId)}/chats/${encodeURIComponent(chatId)}`;
1423
+ }
1424
+ /** Events from a text/event-stream body. `heard` runs on every chunk, pings included. */
1425
+ async function* serverSentEvents(body, heard) {
1426
+ let partial = "";
1427
+ let fields = { data: [] };
1428
+ for await (const chunk of body.pipeThrough(new TextDecoderStream())) {
1429
+ heard();
1430
+ const lines = (partial + chunk).split(/\r?\n/);
1431
+ partial = lines.pop() ?? "";
1432
+ for (const line of lines) if (line === "") {
1433
+ if (fields.data.length) yield {
1434
+ event: fields.event ?? "message",
1435
+ id: fields.id,
1436
+ data: fields.data.join("\n")
1437
+ };
1438
+ fields = { data: [] };
1439
+ } else if (!line.startsWith(":")) {
1440
+ const [field, value] = splitField(line);
1441
+ if (field === "event") fields.event = value;
1442
+ else if (field === "id") fields.id = value;
1443
+ else if (field === "data") fields.data.push(value);
1444
+ }
1445
+ }
1446
+ }
1447
+ /** `field: value`, without the one optional space after the colon. */
1448
+ function splitField(line) {
1449
+ const colon = line.indexOf(":");
1450
+ if (colon < 0) return [line, ""];
1451
+ return [line.slice(0, colon), line.slice(colon + 1).replace(/^ /, "")];
1452
+ }
1453
+ //#endregion
1454
+ //#region ../provider-ensemble/src/auth.ts
1455
+ /** The tokens Ensemble gave Tencil, per Ensemble URL, readable only by this user. */
1456
+ var EnsembleCredentialStore = class {
1457
+ path;
1458
+ constructor(path = join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "tencil", "ensemble-credentials.json")) {
1459
+ this.path = path;
1460
+ }
1461
+ async get(baseUrl) {
1462
+ return (await this.#read())[new URL(baseUrl).origin];
1463
+ }
1464
+ async set(baseUrl, token) {
1465
+ const tokens = await this.#read();
1466
+ tokens[new URL(baseUrl).origin] = token;
1467
+ await mkdir(dirname(this.path), { recursive: true });
1468
+ await writeFile(this.path, `${JSON.stringify(tokens, null, 2)}\n`, { mode: 384 });
1469
+ await chmod(this.path, 384);
1470
+ }
1471
+ async #read() {
1472
+ try {
1473
+ return JSON.parse(await readFile(this.path, "utf8"));
1474
+ } catch {
1475
+ return {};
1476
+ }
1477
+ }
1478
+ };
1479
+ //#endregion
1480
+ //#region ../provider-ensemble/src/folders.ts
1481
+ const run$2 = promisify(execFile);
1482
+ /**
1483
+ * The Ensemble target for a page whose dev server runs in `folder`:
1484
+ * - inside an Ensemble project's folder, it's the user's own checkout: each pin starts a thread.
1485
+ * - on the branch of one open thread, it's that thread's workspace: pins go to the thread.
1486
+ * - a worktree of a project's repository counts as that project.
1487
+ */
1488
+ async function targetForFolder(client, folder) {
1489
+ const dir = await realpath(folder).catch(() => folder);
1490
+ const [projects, git] = await Promise.all([client.projects(), gitInfo(dir)]);
1491
+ const local = (await Promise.all(projects.map(async (project) => project.source.kind === "local" ? {
1492
+ project,
1493
+ path: await realpath(project.source.path).catch(() => "")
1494
+ } : void 0))).filter((entry) => entry?.path);
1495
+ const own = deepest(local, dir);
1496
+ if (own) return {
1497
+ kind: "project",
1498
+ project: own
1499
+ };
1500
+ if (git?.branch) {
1501
+ const threads = (await client.threads()).filter((thread) => thread.branch === git.branch);
1502
+ if (threads.length === 1 && threads[0]) return {
1503
+ kind: "thread",
1504
+ threadId: threads[0].id
1505
+ };
1506
+ }
1507
+ if (git?.main) {
1508
+ const project = deepest(local, join(git.main, relative(git.top, dir)));
1509
+ if (project) return {
1510
+ kind: "project",
1511
+ project
1512
+ };
1513
+ }
1514
+ return {
1515
+ kind: "missing",
1516
+ repository: git?.main ?? git?.top ?? dir
1517
+ };
1518
+ }
1519
+ /** The project whose folder holds `dir` most closely. */
1520
+ function deepest(folders, dir) {
1521
+ let best;
1522
+ for (const { project, path } of folders) {
1523
+ if (dir !== path && !dir.startsWith(path.endsWith(sep) ? path : `${path}${sep}`)) continue;
1524
+ const depth = path.split(sep).length;
1525
+ if (!best || depth > best.depth) best = {
1526
+ project,
1527
+ depth
1528
+ };
1529
+ }
1530
+ return best?.project;
1531
+ }
1532
+ async function gitInfo(dir) {
1533
+ try {
1534
+ const { stdout } = await run$2("git", [
1535
+ "-C",
1536
+ dir,
1537
+ "rev-parse",
1538
+ "--abbrev-ref",
1539
+ "HEAD",
1540
+ "--show-toplevel",
1541
+ "--path-format=absolute",
1542
+ "--git-common-dir"
1543
+ ], {
1544
+ timeout: 3e3,
1545
+ windowsHide: true
1546
+ });
1547
+ const [branch, top, common] = stdout.trim().split("\n");
1548
+ if (!top || !common) return void 0;
1549
+ const realTop = await realpath(top).catch(() => top);
1550
+ const repository = basename(common) === ".git" ? dirname(common) : void 0;
1551
+ const main = repository && await realpath(repository).catch(() => repository);
1552
+ return {
1553
+ branch: branch && branch !== "HEAD" ? branch : void 0,
1554
+ top: realTop,
1555
+ main: main && main !== realTop ? main : void 0
1556
+ };
1557
+ } catch {
1558
+ return;
1559
+ }
1560
+ }
1561
+ //#endregion
1562
+ //#region ../provider-ensemble/src/projects.ts
1563
+ const ROOT_PREFIX = "ensemble://thread/";
1564
+ /** The project root Tencil uses for an Ensemble thread: `ensemble://thread/<id>`. */
1565
+ function ensembleRoot(threadId) {
1566
+ return `${ROOT_PREFIX}${encodeURIComponent(threadId)}`;
1567
+ }
1568
+ /** The thread an `ensemble://thread/<id>` root names; undefined for a folder. */
1569
+ function ensembleThreadId(root) {
1570
+ return root.startsWith(ROOT_PREFIX) ? decodeURIComponent(root.slice(18)) : void 0;
1571
+ }
1572
+ /** Open Ensemble threads for the project picker, forwarded ones included; [] until paired. */
1573
+ async function listEnsembleProjects(options = {}) {
1574
+ return (await (await pairedClient(options))?.threads() ?? []).map((thread) => ({
1575
+ workspaceRoot: ensembleRoot(thread.id),
1576
+ title: thread.title
1577
+ }));
1578
+ }
1579
+ /** The root of the Ensemble thread whose dev server listens on `port`, when there is one. */
1580
+ async function ensembleProjectForPort(port, options = {}) {
1581
+ const threads = await (await pairedClient(options))?.threads({ port }) ?? [];
1582
+ return threads.length === 1 && threads[0] ? ensembleRoot(threads[0].id) : void 0;
1583
+ }
1584
+ async function pairedClient(options) {
1585
+ const baseUrl = options.baseUrl ?? ensembleUrl();
1586
+ const token = await (options.credentials ?? new EnsembleCredentialStore()).get(baseUrl);
1587
+ return token ? new EnsembleClient({
1588
+ baseUrl,
1589
+ token,
1590
+ timeoutMs: 1500
1591
+ }) : void 0;
1592
+ }
1593
+ //#endregion
1594
+ //#region ../provider-ensemble/src/thread-feed.ts
1595
+ /**
1596
+ * One Ensemble thread's feed, shared by every pin in it. It keeps each chat's state,
1597
+ * so a watcher that starts late gets it replayed, and resumes from the last event
1598
+ * after a drop.
1599
+ */
1600
+ var ThreadFeed = class {
1601
+ threadId;
1602
+ options;
1603
+ #chats = /* @__PURE__ */ new Map();
1604
+ #watchers = /* @__PURE__ */ new Map();
1605
+ #cursor;
1606
+ #following;
1607
+ #archived = false;
1608
+ constructor(threadId, options) {
1609
+ this.threadId = threadId;
1610
+ this.options = options;
1611
+ }
1612
+ get watched() {
1613
+ return this.#watchers.size > 0;
1614
+ }
1615
+ /** Replay the chat's state to `sink`, then send it live updates. Call `follow` to go live. */
1616
+ watch(chatId, sink) {
1617
+ if (this.#archived) {
1618
+ sink.gone();
1619
+ return () => {};
1620
+ }
1621
+ const watchers = this.#watchers.get(chatId) ?? /* @__PURE__ */ new Set();
1622
+ this.#watchers.set(chatId, watchers);
1623
+ watchers.add(sink);
1624
+ const chat = this.#chats.get(chatId);
1625
+ if (chat) replay(chat, sink);
1626
+ return () => {
1627
+ watchers.delete(sink);
1628
+ if (!watchers.size) this.#watchers.delete(chatId);
1629
+ if (!this.watched) this.stop();
1630
+ };
1631
+ }
1632
+ /** Follow the feed while anyone watches; does nothing when it already does. */
1633
+ follow(client) {
1634
+ if (this.#following || this.#archived || !this.watched) return;
1635
+ const following = new AbortController();
1636
+ this.#following = following;
1637
+ this.#follow(client, following.signal).finally(() => {
1638
+ if (this.#following === following) this.#following = void 0;
1639
+ });
1640
+ }
1641
+ stop() {
1642
+ this.#following?.abort();
1643
+ this.#following = void 0;
1644
+ }
1645
+ async #follow(client, signal) {
1646
+ const minMs = this.options.timeouts?.reconnectMinMs ?? 1e3;
1647
+ const maxMs = this.options.timeouts?.reconnectMaxMs ?? 3e4;
1648
+ let delayMs = minMs;
1649
+ while (!signal.aborted) {
1650
+ try {
1651
+ const events = client.feed(this.threadId, {
1652
+ after: this.#cursor,
1653
+ signal,
1654
+ silenceMs: this.options.timeouts?.silenceMs
1655
+ });
1656
+ for await (const { id, event } of events) {
1657
+ this.#apply(event);
1658
+ if (id !== void 0) this.#cursor = id;
1659
+ delayMs = minMs;
1660
+ }
1661
+ } catch (error) {
1662
+ if (signal.aborted) return;
1663
+ if (error instanceof EnsembleUnauthorizedError) return this.options.onUnauthorized();
1664
+ if (error instanceof EnsembleHttpError && error.status === 404) return this.#apply({
1665
+ type: "archived",
1666
+ threadId: this.threadId
1667
+ });
1668
+ this.options.log?.(`Reconnecting to Ensemble's feed: ${errorMessage$2(error)}`);
1669
+ }
1670
+ await setTimeout$1(delayMs, void 0, {
1671
+ signal,
1672
+ ref: false
1673
+ }).catch(() => {});
1674
+ delayMs = Math.min(delayMs * 2, maxMs);
1675
+ }
1676
+ }
1677
+ #apply(event) {
1678
+ switch (event.type) {
1679
+ case "archived":
1680
+ this.#archived = true;
1681
+ this.stop();
1682
+ for (const sinks of this.#watchers.values()) for (const sink of sinks) sink.gone();
1683
+ return;
1684
+ case "chat":
1685
+ this.#upsertMessages(event.chatId, event.messages);
1686
+ this.#replaceSteps(event.chatId, event.steps);
1687
+ this.#setStatus(event.chatId, event.status);
1688
+ return;
1689
+ case "message":
1690
+ this.#upsertMessages(event.chatId, [event.message]);
1691
+ return;
1692
+ case "steps":
1693
+ this.#replaceSteps(event.chatId, event.steps);
1694
+ return;
1695
+ case "status":
1696
+ this.#setStatus(event.chatId, event.status);
1697
+ return;
1698
+ }
1699
+ }
1700
+ #upsertMessages(chatId, messages) {
1701
+ const chat = this.#chat(chatId);
1702
+ for (const message of messages) {
1703
+ const createdAt = chat.messages.get(message.id)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
1704
+ const next = {
1705
+ ...message,
1706
+ createdAt
1707
+ };
1708
+ chat.messages.set(message.id, next);
1709
+ for (const sink of this.#sinks(chatId)) sink.message(next);
1710
+ }
1711
+ }
1712
+ /** Ensemble sends the turn's whole list of steps each time. */
1713
+ #replaceSteps(chatId, steps) {
1714
+ const chat = this.#chat(chatId);
1715
+ const previous = chat.steps;
1716
+ chat.steps = /* @__PURE__ */ new Map();
1717
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1718
+ for (const step of steps) {
1719
+ const before = previous.get(step.id);
1720
+ const next = {
1721
+ ...step,
1722
+ startedAt: before?.startedAt ?? now,
1723
+ ...step.status === "running" ? {} : { endedAt: before?.endedAt ?? now }
1724
+ };
1725
+ chat.steps.set(step.id, next);
1726
+ for (const sink of this.#sinks(chatId)) sink.step?.(next);
1727
+ }
1728
+ }
1729
+ #setStatus(chatId, status) {
1730
+ this.#chat(chatId).status = status;
1731
+ for (const sink of this.#sinks(chatId)) sink.status(status);
1732
+ }
1733
+ #chat(chatId) {
1734
+ let chat = this.#chats.get(chatId);
1735
+ if (!chat) {
1736
+ chat = {
1737
+ messages: /* @__PURE__ */ new Map(),
1738
+ steps: /* @__PURE__ */ new Map()
1739
+ };
1740
+ this.#chats.set(chatId, chat);
1741
+ }
1742
+ return chat;
1743
+ }
1744
+ #sinks(chatId) {
1745
+ return this.#watchers.get(chatId) ?? [];
1746
+ }
1747
+ };
1748
+ function replay(chat, sink) {
1749
+ for (const message of chat.messages.values()) sink.message(message);
1750
+ for (const step of chat.steps.values()) sink.step?.(step);
1751
+ if (chat.status) sink.status(chat.status);
1752
+ }
1753
+ //#endregion
1754
+ //#region ../provider-ensemble/src/ensemble-provider.ts
1755
+ /**
1756
+ * Sends pins to the Ensemble thread serving the page, one chat per pin, through
1757
+ * Ensemble's public local API. A page served from an Ensemble project's own folder
1758
+ * starts a thread per pin instead. Pins in a thread share one feed.
1759
+ */
1760
+ var EnsembleProvider = class {
1761
+ options;
1762
+ id = "ensemble";
1763
+ label = "Ensemble";
1764
+ #baseUrl;
1765
+ #target;
1766
+ #credentials;
1767
+ #feeds = /* @__PURE__ */ new Map();
1768
+ #listeners = /* @__PURE__ */ new Set();
1769
+ #info = {
1770
+ id: "ensemble",
1771
+ label: "Ensemble",
1772
+ state: "connecting"
1773
+ };
1774
+ /** Set while Ensemble accepts the token and the thread is open. */
1775
+ #client;
1776
+ #starting;
1777
+ #pairing;
1778
+ #retry;
1779
+ #disposed = false;
1780
+ constructor(options) {
1781
+ this.options = options;
1782
+ this.#baseUrl = new URL(options.baseUrl ?? ensembleUrl()).origin;
1783
+ const threadId = ensembleThreadId(options.projectRoot);
1784
+ if (threadId) this.#target = {
1785
+ kind: "thread",
1786
+ threadId
1787
+ };
1788
+ this.#credentials = options.credentials ?? new EnsembleCredentialStore();
1789
+ }
1790
+ info() {
1791
+ return this.#info;
1792
+ }
1793
+ onInfoChange(listener) {
1794
+ this.#listeners.add(listener);
1795
+ return () => this.#listeners.delete(listener);
1796
+ }
1797
+ start() {
1798
+ this.#starting ??= this.#connect().finally(() => {
1799
+ this.#starting = void 0;
1800
+ });
1801
+ return this.#starting;
1802
+ }
1803
+ /** Ask the user to allow Tencil in Ensemble, then connect with the new token. */
1804
+ pair() {
1805
+ this.#pairing ??= this.#pair().finally(() => {
1806
+ this.#pairing = void 0;
1807
+ });
1808
+ return this.#pairing;
1809
+ }
1810
+ async listThreads() {
1811
+ const target = await this.#requireTarget();
1812
+ const [name, threads] = target.kind === "thread" ? await this.#call(async (client) => {
1813
+ const thread = await client.thread(target.threadId);
1814
+ return [thread.title, [thread]];
1815
+ }) : [target.project.name, await this.#call((client) => client.threads({ project: target.project.id }))];
1816
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1817
+ return {
1818
+ project: { name },
1819
+ threads: threads.flatMap((thread) => thread.chats.map((chat) => {
1820
+ const id = chatThreadId(thread.id, chat.id);
1821
+ return {
1822
+ id,
1823
+ title: chat.title,
1824
+ status: chat.status,
1825
+ updatedAt,
1826
+ url: this.threadUrl(id)
1827
+ };
1828
+ }))
1829
+ };
1830
+ }
1831
+ threadUrl(providerThreadId) {
1832
+ return ensembleRoot(parseChatThreadId(providerThreadId).threadId);
1833
+ }
1834
+ async createThread(input) {
1835
+ const target = await this.#requireTarget();
1836
+ const chat = {
1837
+ title: input.title,
1838
+ prompt: input.text,
1839
+ attachments: input.attachments.map(toEnsembleImage),
1840
+ ...input.model ? { model: input.model } : {}
1841
+ };
1842
+ const providerThreadId = target.kind === "thread" ? chatThreadId(target.threadId, (await this.#call((client) => client.createChat(target.threadId, chat))).id) : await this.#call(async (client) => {
1843
+ const thread = await client.createThread({
1844
+ projectId: target.project.id,
1845
+ ...chat
1846
+ });
1847
+ return chatThreadId(thread.id, thread.chats[0]?.id ?? "main");
1848
+ });
1849
+ return {
1850
+ providerThreadId,
1851
+ url: this.threadUrl(providerThreadId),
1852
+ archivable: target.kind === "project"
1853
+ };
1854
+ }
1855
+ async archive(providerThreadId) {
1856
+ const { threadId, chatId } = parseChatThreadId(providerThreadId);
1857
+ await this.#call(async (client) => {
1858
+ if ((await client.thread(threadId)).chats.some((chat) => chat.id !== chatId)) return;
1859
+ await client.archiveThread(threadId);
1860
+ });
1861
+ }
1862
+ async reopen(providerThreadId) {
1863
+ const { threadId } = parseChatThreadId(providerThreadId);
1864
+ await this.#call((client) => client.reopenThread(threadId));
1865
+ }
1866
+ async sendMessage(input) {
1867
+ const { threadId, chatId } = parseChatThreadId(input.providerThreadId);
1868
+ await this.#call((client) => client.sendMessage(threadId, chatId, {
1869
+ text: input.text,
1870
+ attachments: input.attachments.map(toEnsembleImage)
1871
+ }));
1872
+ }
1873
+ async interrupt(providerThreadId) {
1874
+ const { threadId, chatId } = parseChatThreadId(providerThreadId);
1875
+ await this.#call((client) => client.stop(threadId, chatId));
1876
+ }
1877
+ watch(providerThreadId, sink) {
1878
+ const { threadId, chatId } = parseChatThreadId(providerThreadId);
1879
+ let feed = this.#feeds.get(threadId);
1880
+ if (!feed) {
1881
+ feed = new ThreadFeed(threadId, {
1882
+ onUnauthorized: () => this.#unauthorized(),
1883
+ log: this.options.log,
1884
+ timeouts: this.options.timeouts
1885
+ });
1886
+ this.#feeds.set(threadId, feed);
1887
+ }
1888
+ const unwatch = feed.watch(chatId, sink);
1889
+ if (this.#client) feed.follow(this.#client);
1890
+ return () => {
1891
+ unwatch();
1892
+ if (!feed.watched) this.#feeds.delete(threadId);
1893
+ };
1894
+ }
1895
+ async dispose() {
1896
+ this.#disposed = true;
1897
+ clearTimeout(this.#retry);
1898
+ for (const feed of this.#feeds.values()) feed.stop();
1899
+ this.#feeds.clear();
1900
+ }
1901
+ async #connect() {
1902
+ clearTimeout(this.#retry);
1903
+ if (!await new EnsembleClient({ baseUrl: this.#baseUrl }).isRunning()) return this.#retryLater("Ensemble isn't running. Open the Ensemble app.");
1904
+ const token = await this.#credentials.get(this.#baseUrl);
1905
+ if (!token) return this.#unauthorized();
1906
+ const client = new EnsembleClient({
1907
+ baseUrl: this.#baseUrl,
1908
+ token,
1909
+ timeoutMs: this.options.timeouts?.requestMs
1910
+ });
1911
+ try {
1912
+ let target = this.#target;
1913
+ if (!target) {
1914
+ const found = await targetForFolder(client, this.options.projectRoot);
1915
+ if (found.kind === "missing") return this.#retryLater(`${basename(found.repository)} isn't in Ensemble yet. Add ${tildify(found.repository)} as a project in Ensemble.`);
1916
+ target = found;
1917
+ }
1918
+ const label = target.kind === "thread" ? (await client.thread(target.threadId)).title : `${target.project.name} · new thread per pin`;
1919
+ if (this.#disposed) return;
1920
+ this.#target = target;
1921
+ this.#client = client;
1922
+ this.#setInfo({
1923
+ state: "ready",
1924
+ target: label
1925
+ });
1926
+ for (const feed of this.#feeds.values()) feed.follow(client);
1927
+ } catch (error) {
1928
+ if (error instanceof EnsembleUnauthorizedError) return this.#unauthorized();
1929
+ if (error instanceof EnsembleHttpError && error.status === 404) return this.#setInfo({
1930
+ state: "unavailable",
1931
+ detail: "This Ensemble thread is closed. Choose an open one."
1932
+ });
1933
+ this.#retryLater(`Ensemble didn't answer: ${errorMessage$2(error)}`);
1934
+ }
1935
+ }
1936
+ async #pair() {
1937
+ this.#setInfo({
1938
+ state: "connecting",
1939
+ detail: "Allow Tencil in the Ensemble app."
1940
+ });
1941
+ try {
1942
+ const token = await new EnsembleClient({ baseUrl: this.#baseUrl }).connect();
1943
+ await this.#credentials.set(this.#baseUrl, token);
1944
+ } catch (error) {
1945
+ this.#setInfo({
1946
+ state: "unauthorized",
1947
+ canPair: true,
1948
+ detail: errorMessage$2(error)
1949
+ });
1950
+ throw error;
1951
+ }
1952
+ await this.#starting;
1953
+ await this.start();
1954
+ }
1955
+ /** Run a call once connected; a refused token asks the user to pair again. */
1956
+ async #call(call) {
1957
+ if (!this.#client) await this.start();
1958
+ const client = this.#client;
1959
+ if (!client) throw new Error(this.#info.detail ?? "Not connected to Ensemble");
1960
+ try {
1961
+ return await call(client);
1962
+ } catch (error) {
1963
+ if (error instanceof EnsembleUnauthorizedError) this.#unauthorized();
1964
+ throw error;
1965
+ }
1966
+ }
1967
+ async #requireTarget() {
1968
+ if (!this.#target) await this.start();
1969
+ if (!this.#target) throw new Error(this.#info.detail ?? "Not connected to Ensemble");
1970
+ return this.#target;
1971
+ }
1972
+ #unauthorized() {
1973
+ this.#client = void 0;
1974
+ for (const feed of this.#feeds.values()) feed.stop();
1975
+ this.#setInfo({
1976
+ state: "unauthorized",
1977
+ canPair: true,
1978
+ detail: "Not connected to Ensemble. Pair, then allow Tencil in the Ensemble app."
1979
+ });
1980
+ }
1981
+ #retryLater(detail) {
1982
+ this.#client = void 0;
1983
+ this.#setInfo({
1984
+ state: "unavailable",
1985
+ detail
1986
+ });
1987
+ if (this.#disposed) return;
1988
+ this.#retry = setTimeout(() => void this.start(), this.options.timeouts?.retryMs ?? 5e3);
1989
+ this.#retry.unref?.();
1990
+ }
1991
+ #setInfo(next) {
1992
+ if (this.#disposed) return;
1993
+ this.#info = {
1994
+ id: this.id,
1995
+ label: this.label,
1996
+ ...next
1997
+ };
1998
+ for (const listener of this.#listeners) listener(this.#info);
1999
+ }
2000
+ };
2001
+ /** A pin's id is its Ensemble thread and chat: `<threadId>/<chatId>`. */
2002
+ function chatThreadId(threadId, chatId) {
2003
+ return `${threadId}/${chatId}`;
2004
+ }
2005
+ function parseChatThreadId(providerThreadId) {
2006
+ const [threadId, chatId, ...rest] = providerThreadId.split("/");
2007
+ if (!threadId || !chatId || rest.length) throw new Error(`Not an Ensemble chat: ${providerThreadId}`);
2008
+ return {
2009
+ threadId,
2010
+ chatId
2011
+ };
2012
+ }
2013
+ function tildify(path) {
2014
+ const home = homedir();
2015
+ return path === home || path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
2016
+ }
2017
+ function toEnsembleImage(image) {
2018
+ return {
2019
+ name: image.name,
2020
+ mediaType: image.mimeType,
2021
+ data: image.dataUrl.slice(image.dataUrl.indexOf(",") + 1)
2022
+ };
2023
+ }
1213
2024
  //#endregion
1214
2025
  //#region src/daemon/project-resolver.ts
1215
2026
  const run$1 = promisify(execFile);
@@ -1219,35 +2030,41 @@ const defaultExec = async (command, args) => (await run$1(command, args, {
1219
2030
  })).stdout;
1220
2031
  /**
1221
2032
  * Works out which project folder a page belongs to:
1222
- * 1. what the user picked for this address before,
2033
+ * 1. the Ensemble thread whose dev server listens on the port,
1223
2034
  * 2. the repository root the Vite or Next loader sent, if it's a git checkout,
1224
- * 3. the dev server's working directory, found from the port it listens on.
1225
- * Returns undefined when neither works; the overlay then asks.
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.
1226
2040
  */
1227
2041
  var ProjectResolver = class {
1228
2042
  #memory;
1229
2043
  #exec;
1230
2044
  #platform;
2045
+ #ensembleForPort;
1231
2046
  constructor(options) {
1232
2047
  this.#memory = new OriginMemory(join(options.dataDir, "origins.json"));
1233
2048
  this.#exec = options.exec ?? defaultExec;
1234
2049
  this.#platform = options.platform ?? process.platform;
2050
+ this.#ensembleForPort = options.ensembleForPort;
1235
2051
  }
1236
2052
  async resolve(pageUrl, claimedRoot) {
1237
2053
  const origin = safeOrigin(pageUrl);
1238
2054
  if (!origin) return void 0;
1239
- const remembered = await this.#memory.get(origin);
1240
- if (remembered && existsSync(remembered)) return remembered;
1241
- if (claimedRoot && isGitRoot(claimedRoot)) return resolve(claimedRoot);
1242
2055
  const port = portOf(origin);
1243
- if (!port) return void 0;
1244
- const folder = await this.folderForPort(port).catch(() => void 0);
1245
- return folder ? projectRoot(folder) : void 0;
2056
+ 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;
1246
2063
  }
1247
2064
  /** Remember the user's choice for an address (from the overlay's project picker). */
1248
2065
  remember(pageUrl, root) {
1249
2066
  const origin = safeOrigin(pageUrl);
1250
- return origin ? this.#memory.set(origin, resolve(root)) : Promise.resolve();
2067
+ return origin ? this.#memory.set(origin, projectKey(root)) : Promise.resolve();
1251
2068
  }
1252
2069
  /**
1253
2070
  * Folder of the process listening on `port`: its working directory, or its script's
@@ -1276,11 +2093,7 @@ var ProjectResolver = class {
1276
2093
  ]).catch(() => ""));
1277
2094
  }
1278
2095
  async #listeners(port) {
1279
- if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", [
1280
- "-ano",
1281
- "-p",
1282
- "TCP"
1283
- ]), port);
2096
+ if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", ["-ano"]), port);
1284
2097
  try {
1285
2098
  return parsePids(await this.#exec("lsof", [
1286
2099
  "-nP",
@@ -1327,6 +2140,10 @@ var ProjectResolver = class {
1327
2140
  function isGitRoot(folder) {
1328
2141
  return isAbsolute(folder) && existsSync(join(folder, ".git"));
1329
2142
  }
2143
+ /** How the daemon keys a project: an `ensemble://thread/<id>` root as is, a folder by its absolute path. */
2144
+ function projectKey(root) {
2145
+ return ensembleThreadId(root) === void 0 ? resolve(root) : root;
2146
+ }
1330
2147
  /** Closest folder with a package.json at or above `folder`, or `folder` itself. */
1331
2148
  function projectRoot(folder) {
1332
2149
  let dir = resolve(folder);
@@ -3301,7 +4118,7 @@ function errorMessage(error) {
3301
4118
  }
3302
4119
  //#endregion
3303
4120
  //#region src/version.ts
3304
- const VERSION = "0.8.0";
4121
+ const VERSION = "0.9.0";
3305
4122
  //#endregion
3306
4123
  //#region src/daemon/thread-store.ts
3307
4124
  const StoreFile = z.object({
@@ -3320,7 +4137,7 @@ function defaultDataDir() {
3320
4137
  * shared between two bridges.
3321
4138
  */
3322
4139
  function projectStorePath(projectRoot, dataDir = defaultDataDir()) {
3323
- const root = resolve(projectRoot);
4140
+ const root = projectKey(projectRoot);
3324
4141
  const hash = createHash("sha256").update(root).digest("hex").slice(0, 10);
3325
4142
  const slug = basename(root).replace(/[^a-z0-9._-]+/gi, "-").slice(0, 40) || "project";
3326
4143
  return join(dataDir, "projects", `${slug}-${hash}.json`);
@@ -3336,7 +4153,7 @@ var FileThreadStore = class {
3336
4153
  #writeTimer;
3337
4154
  #writing = Promise.resolve();
3338
4155
  constructor(projectRoot, dataDir) {
3339
- this.#root = resolve(projectRoot);
4156
+ this.#root = projectKey(projectRoot);
3340
4157
  this.path = projectStorePath(this.#root, dataDir);
3341
4158
  }
3342
4159
  async load() {
@@ -3395,14 +4212,25 @@ var FileThreadStore = class {
3395
4212
  };
3396
4213
  //#endregion
3397
4214
  //#region src/daemon/agents.ts
3398
- const PROVIDERS = ["t3code", "claude-code"];
3399
- const PROVIDER_OPTIONS = [{
3400
- id: "t3code",
3401
- label: "T3 Code"
3402
- }, {
3403
- id: "claude-code",
3404
- label: "Claude Code"
3405
- }];
4215
+ const PROVIDERS = [
4216
+ "t3code",
4217
+ "claude-code",
4218
+ "ensemble"
4219
+ ];
4220
+ const PROVIDER_OPTIONS = [
4221
+ {
4222
+ id: "t3code",
4223
+ label: "T3 Code"
4224
+ },
4225
+ {
4226
+ id: "claude-code",
4227
+ label: "Claude Code"
4228
+ },
4229
+ {
4230
+ id: "ensemble",
4231
+ label: "Ensemble"
4232
+ }
4233
+ ];
3406
4234
  const providerLabel = (id) => PROVIDER_OPTIONS.find((option) => option.id === id)?.label ?? id;
3407
4235
  const SettingsFile$1 = z.object({
3408
4236
  version: z.literal(1),
@@ -3430,23 +4258,33 @@ async function saveProvider(provider, dataDir = defaultDataDir()) {
3430
4258
  }, null, 2)}\n`);
3431
4259
  await rename(`${path}.tmp`, path);
3432
4260
  }
3433
- /** Which agents this machine has: a paired or running T3 Code, an installed Claude Code. */
4261
+ /**
4262
+ * Which agents this machine has: a paired or running T3 Code, an installed
4263
+ * Claude Code, a running Ensemble app.
4264
+ */
3434
4265
  async function detectAgents(options = {}) {
3435
- const [t3code, claudeCode] = await Promise.all([hasT3Code(options.t3Url), hasClaudeCode()]);
4266
+ const [t3code, claudeCode, ensemble] = await Promise.all([
4267
+ hasT3Code(options.t3Url),
4268
+ hasClaudeCode(),
4269
+ hasEnsemble()
4270
+ ]);
3436
4271
  return {
3437
4272
  t3code,
3438
- "claude-code": claudeCode
4273
+ "claude-code": claudeCode,
4274
+ ensemble
3439
4275
  };
3440
4276
  }
3441
4277
  /**
3442
4278
  * The agent for projects that haven't picked one: the saved choice, else the
3443
- * only agent found, else T3 Code.
4279
+ * first agent found (T3 Code, Claude Code, Ensemble), else T3 Code.
3444
4280
  */
3445
4281
  async function machineProvider(options = {}) {
3446
4282
  const saved = await savedProvider(options.dataDir);
3447
4283
  if (saved) return saved;
3448
4284
  const found = await detectAgents(options);
3449
- return found["claude-code"] && !found.t3code ? "claude-code" : "t3code";
4285
+ if (found.t3code) return "t3code";
4286
+ if (found["claude-code"]) return "claude-code";
4287
+ return found.ensemble ? "ensemble" : "t3code";
3450
4288
  }
3451
4289
  async function hasT3Code(t3Url) {
3452
4290
  const store = new CredentialStore();
@@ -3458,6 +4296,10 @@ async function hasT3Code(t3Url) {
3458
4296
  return false;
3459
4297
  }
3460
4298
  }
4299
+ /** Ensemble's app, running now; finding it needs no token. */
4300
+ function hasEnsemble() {
4301
+ return new EnsembleClient().isRunning();
4302
+ }
3461
4303
  /** `claude` on the PATH, or its config folder (login services get a bare PATH). */
3462
4304
  async function hasClaudeCode() {
3463
4305
  const names = process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"];
@@ -4371,9 +5213,14 @@ async function startDaemon(options = {}) {
4371
5213
  const knownHosts = knownHostsFor(addresses, allowedOrigins);
4372
5214
  const dataDir = options.dataDir ?? defaultDataDir();
4373
5215
  const log = options.log ?? (() => {});
5216
+ const ensembleOptions = {
5217
+ baseUrl: options.ensemble?.url,
5218
+ credentials: options.ensemble?.credentials
5219
+ };
4374
5220
  const resolver = new ProjectResolver({
4375
5221
  dataDir,
4376
- exec: options.exec
5222
+ exec: options.exec,
5223
+ ensembleForPort: (port) => ensembleProjectForPort(port, ensembleOptions)
4377
5224
  });
4378
5225
  const resolveProject = options.resolveProject ?? ((pageUrl, root) => resolver.resolve(pageUrl, root));
4379
5226
  const sessions = /* @__PURE__ */ new Map();
@@ -4389,6 +5236,11 @@ async function startDaemon(options = {}) {
4389
5236
  installDir: claudeCodeDir,
4390
5237
  log: providerLog
4391
5238
  });
5239
+ if (id === "ensemble") return new EnsembleProvider({
5240
+ projectRoot: root,
5241
+ ...ensembleOptions,
5242
+ log: providerLog
5243
+ });
4392
5244
  const { url, token, ...t3 } = options.t3 ?? {};
4393
5245
  return new T3CodeProvider({
4394
5246
  ...t3,
@@ -4400,16 +5252,16 @@ async function startDaemon(options = {}) {
4400
5252
  });
4401
5253
  });
4402
5254
  const session = (root) => {
4403
- const key = resolve(root);
5255
+ const key = projectKey(root);
4404
5256
  let pending = sessions.get(key);
4405
5257
  if (!pending) {
4406
5258
  pending = (async () => {
4407
5259
  const providers = new ProjectProviders({
4408
5260
  choices: PROVIDER_OPTIONS,
4409
- fallback: options.provider ?? await machineProvider({
5261
+ fallback: options.provider ?? (ensembleThreadId(key) === void 0 ? await machineProvider({
4410
5262
  dataDir,
4411
5263
  t3Url
4412
- }),
5264
+ }) : "ensemble"),
4413
5265
  create: (id) => createProvider(key, id),
4414
5266
  settings: new FileProjectSettings(projectSettingsPath(key, dataDir))
4415
5267
  });
@@ -4439,21 +5291,29 @@ async function startDaemon(options = {}) {
4439
5291
  }
4440
5292
  return pending;
4441
5293
  };
4442
- /** Projects either agent knows, offered when a page's project can't be worked out. */
5294
+ /** Projects any agent knows, offered when a page's project can't be worked out. */
4443
5295
  const choices = async () => {
4444
- const [t3, claude] = await Promise.all([listT3Projects({
4445
- baseUrl: t3Url,
4446
- token: options.t3?.token ?? process.env.TENCIL_T3_TOKEN,
4447
- credentials: options.t3?.credentials
4448
- }).catch(() => []), listClaudeCodeProjects({ installDir: claudeCodeDir }).catch(() => [])]);
5296
+ const [t3, claude, ensemble] = await Promise.all([
5297
+ listT3Projects({
5298
+ baseUrl: t3Url,
5299
+ token: options.t3?.token ?? process.env.TENCIL_T3_TOKEN,
5300
+ credentials: options.t3?.credentials
5301
+ }).catch(() => []),
5302
+ listClaudeCodeProjects({ installDir: claudeCodeDir }).catch(() => []),
5303
+ listEnsembleProjects(ensembleOptions).catch(() => [])
5304
+ ]);
4449
5305
  const byRoot = /* @__PURE__ */ new Map();
4450
- for (const project of [...t3, ...claude]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
5306
+ for (const project of [
5307
+ ...t3,
5308
+ ...claude,
5309
+ ...ensemble
5310
+ ]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
4451
5311
  root: project.workspaceRoot,
4452
5312
  title: project.title
4453
5313
  });
4454
5314
  return [...byRoot.values()];
4455
5315
  };
4456
- const noChoicesHint = "No projects found. Open this page's project in T3 Code, or run claude in it once.";
5316
+ const noChoicesHint = "No projects found. Open this page's project in T3 Code or Ensemble, or run claude in it once.";
4457
5317
  const settled = async () => (await Promise.allSettled(sessions.values())).filter((r) => r.status === "fulfilled").map((r) => r.value);
4458
5318
  let statuses = [];
4459
5319
  const refreshStatuses = async () => {
@@ -4666,4 +5526,4 @@ function resolveOverlayPath() {
4666
5526
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
4667
5527
  }
4668
5528
  //#endregion
4669
- export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E, renderPrompt as F, stripContext as I, ProjectResolver as M, projectRoot as N, exchangePairingCredential as O, Bridge as P, 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 };
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 };