tencil 0.7.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.
- package/README.md +35 -6
- package/dist/cli.mjs +51 -471
- package/dist/{cloud-jOobzTY9.d.mts → cloud-dXtv3DCr.d.mts} +1 -1
- package/dist/{index-BRcZL2Ov.d.mts → index-CexSk5_J.d.mts} +29 -1
- package/dist/index.d.mts +77 -8
- package/dist/index.mjs +1 -1
- package/dist/{loader-BevujQ44.mjs → loader-th3V-C7L.mjs} +7 -2
- package/dist/next.d.mts +6 -3
- package/dist/next.mjs +17 -3
- package/dist/overlay.global.js +44 -23
- package/dist/react.d.mts +1 -1
- package/dist/react.mjs +2 -2
- package/dist/{server-1L4Fi2wN.mjs → server-4YposP38.mjs} +1798 -69
- package/dist/source-attributes-Cs2NvuxG.mjs +151 -0
- package/dist/vite.d.mts +1 -1
- package/dist/vite.mjs +3 -151
- package/package.json +7 -6
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { execFile } from "node:child_process";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
2
|
+
import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, 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
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. */
|
|
@@ -116,6 +117,8 @@ const ClientMessage = z.discriminatedUnion("type", [
|
|
|
116
117
|
type: z.literal("hello"),
|
|
117
118
|
protocol: z.literal(1),
|
|
118
119
|
pageUrl: z.string(),
|
|
120
|
+
/** Repository root the page's dev server runs in (Vite and Next integrations). */
|
|
121
|
+
root: z.string().max(4096).optional(),
|
|
119
122
|
build: BuildInfo.optional(),
|
|
120
123
|
/** Tencil Cloud access token; the local daemon has no sign-in. */
|
|
121
124
|
token: z.string().min(1).max(4096).optional()
|
|
@@ -193,7 +196,8 @@ const ClientMessage = z.discriminatedUnion("type", [
|
|
|
193
196
|
z.object({
|
|
194
197
|
type: z.literal("model.select"),
|
|
195
198
|
model: z.string().min(1).nullable()
|
|
196
|
-
})
|
|
199
|
+
}),
|
|
200
|
+
z.object({ type: z.literal("update.start") })
|
|
197
201
|
]);
|
|
198
202
|
z.object({
|
|
199
203
|
id: z.string(),
|
|
@@ -338,7 +342,9 @@ const Thread = z.object({
|
|
|
338
342
|
id: z.string(),
|
|
339
343
|
threadId: z.string().optional(),
|
|
340
344
|
/** Deep link into the provider UI, when it has one. */
|
|
341
|
-
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()
|
|
342
348
|
}),
|
|
343
349
|
/** Tencil Cloud only: the run's commit, pull request and preview. */
|
|
344
350
|
delivery: Delivery.optional(),
|
|
@@ -535,7 +541,7 @@ var Bridge = class {
|
|
|
535
541
|
type: "settings",
|
|
536
542
|
settings: this.#settings()
|
|
537
543
|
}));
|
|
538
|
-
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);
|
|
539
545
|
}
|
|
540
546
|
connect(client) {
|
|
541
547
|
this.#clients.add(client);
|
|
@@ -562,7 +568,8 @@ var Bridge = class {
|
|
|
562
568
|
provider: this.#provider().info(),
|
|
563
569
|
settings: this.#settings(),
|
|
564
570
|
threads: this.#options.store.list(),
|
|
565
|
-
...client.viewer && { viewer: client.viewer }
|
|
571
|
+
...client.viewer && { viewer: client.viewer },
|
|
572
|
+
...this.#options.update && { update: this.#options.update() }
|
|
566
573
|
});
|
|
567
574
|
return;
|
|
568
575
|
case "thread.create":
|
|
@@ -629,10 +636,7 @@ var Bridge = class {
|
|
|
629
636
|
return;
|
|
630
637
|
}
|
|
631
638
|
case "thread.resolve":
|
|
632
|
-
this.#
|
|
633
|
-
...thread,
|
|
634
|
-
resolved: message.resolved
|
|
635
|
-
}));
|
|
639
|
+
await this.#resolve(message.threadId, message.resolved);
|
|
636
640
|
return;
|
|
637
641
|
case "thread.move":
|
|
638
642
|
this.#update(message.threadId, (thread) => ({
|
|
@@ -641,15 +645,18 @@ var Bridge = class {
|
|
|
641
645
|
}));
|
|
642
646
|
return;
|
|
643
647
|
case "thread.delete": {
|
|
644
|
-
const
|
|
648
|
+
const thread = this.#options.store.get(message.threadId);
|
|
645
649
|
this.#draftAttachments.delete(message.threadId);
|
|
646
650
|
if (this.#options.store.delete(message.threadId)) this.#broadcast({
|
|
647
651
|
type: "thread.removed",
|
|
648
652
|
threadId: message.threadId
|
|
649
653
|
});
|
|
650
|
-
if (
|
|
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);
|
|
651
657
|
return;
|
|
652
658
|
}
|
|
659
|
+
case "update.start": throw new Error("Tencil can't update itself here");
|
|
653
660
|
}
|
|
654
661
|
} catch (error) {
|
|
655
662
|
const threadId = "threadId" in message ? message.threadId : void 0;
|
|
@@ -706,7 +713,8 @@ var Bridge = class {
|
|
|
706
713
|
provider: {
|
|
707
714
|
id: provider.id,
|
|
708
715
|
threadId: created.providerThreadId,
|
|
709
|
-
url: created.url
|
|
716
|
+
url: created.url,
|
|
717
|
+
archivable: created.archivable
|
|
710
718
|
}
|
|
711
719
|
}));
|
|
712
720
|
this.#watch(provider.id, created.providerThreadId);
|
|
@@ -793,7 +801,8 @@ var Bridge = class {
|
|
|
793
801
|
provider: {
|
|
794
802
|
id: provider.id,
|
|
795
803
|
threadId: created.providerThreadId,
|
|
796
|
-
url: created.url
|
|
804
|
+
url: created.url,
|
|
805
|
+
archivable: created.archivable
|
|
797
806
|
}
|
|
798
807
|
}));
|
|
799
808
|
}
|
|
@@ -829,7 +838,8 @@ var Bridge = class {
|
|
|
829
838
|
provider: {
|
|
830
839
|
id: provider.id,
|
|
831
840
|
threadId: providerThreadId,
|
|
832
|
-
url: provider.threadUrl(providerThreadId)
|
|
841
|
+
url: provider.threadUrl(providerThreadId),
|
|
842
|
+
archivable: sibling?.provider.archivable
|
|
833
843
|
},
|
|
834
844
|
createdAt: now,
|
|
835
845
|
updatedAt: now
|
|
@@ -878,7 +888,8 @@ var Bridge = class {
|
|
|
878
888
|
provider: {
|
|
879
889
|
id: provider.id,
|
|
880
890
|
threadId: message.providerThreadId,
|
|
881
|
-
url: provider.threadUrl(message.providerThreadId)
|
|
891
|
+
url: provider.threadUrl(message.providerThreadId),
|
|
892
|
+
archivable: sibling?.provider.archivable
|
|
882
893
|
},
|
|
883
894
|
createdAt: now,
|
|
884
895
|
updatedAt: now
|
|
@@ -890,9 +901,9 @@ var Bridge = class {
|
|
|
890
901
|
async #reply(message) {
|
|
891
902
|
const thread = this.#require(message.threadId);
|
|
892
903
|
if (!thread.provider.threadId) throw new Error("This pin has no agent thread yet");
|
|
904
|
+
await this.#resolve(thread.id, false);
|
|
893
905
|
this.#update(thread.id, (current) => ({
|
|
894
906
|
...current,
|
|
895
|
-
resolved: false,
|
|
896
907
|
status: "working",
|
|
897
908
|
statusDetail: void 0,
|
|
898
909
|
steps: void 0,
|
|
@@ -905,6 +916,43 @@ var Bridge = class {
|
|
|
905
916
|
});
|
|
906
917
|
}
|
|
907
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
|
+
/**
|
|
908
956
|
* Subscribe once per provider thread and fan updates out to every bound pin.
|
|
909
957
|
* `replay` re-subscribes an existing watch so a newly bound pin receives the
|
|
910
958
|
* provider's snapshot too.
|
|
@@ -938,7 +986,9 @@ var Bridge = class {
|
|
|
938
986
|
this.#watches.set(key, unwatch);
|
|
939
987
|
}
|
|
940
988
|
#release(providerId, providerThreadId) {
|
|
941
|
-
if (this.#pinsFor(providerId, providerThreadId).length
|
|
989
|
+
if (this.#pinsFor(providerId, providerThreadId).length === 0) this.#unwatch(providerId, providerThreadId);
|
|
990
|
+
}
|
|
991
|
+
#unwatch(providerId, providerThreadId) {
|
|
942
992
|
const key = watchKey(providerId, providerThreadId);
|
|
943
993
|
this.#watches.get(key)?.();
|
|
944
994
|
this.#watches.delete(key);
|
|
@@ -1205,6 +1255,772 @@ function settleInterrupted(thread) {
|
|
|
1205
1255
|
statusDetail: "Bridge stopped before the thread was created"
|
|
1206
1256
|
};
|
|
1207
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
|
+
}
|
|
1208
2024
|
//#endregion
|
|
1209
2025
|
//#region src/daemon/project-resolver.ts
|
|
1210
2026
|
const run$1 = promisify(execFile);
|
|
@@ -1214,49 +2030,70 @@ const defaultExec = async (command, args) => (await run$1(command, args, {
|
|
|
1214
2030
|
})).stdout;
|
|
1215
2031
|
/**
|
|
1216
2032
|
* Works out which project folder a page belongs to:
|
|
1217
|
-
* 1.
|
|
1218
|
-
* 2. the
|
|
1219
|
-
*
|
|
2033
|
+
* 1. the Ensemble thread whose dev server listens on the port,
|
|
2034
|
+
* 2. the repository root the Vite or Next loader sent, if it's a git checkout,
|
|
2035
|
+
* 3. the dev server's working directory, found from the port it listens on,
|
|
2036
|
+
* 4. what the user picked for this address before (a folder or an Ensemble thread).
|
|
2037
|
+
* Picks come last: ports get reused (5173 is every Vite app's default), so a pick
|
|
2038
|
+
* only stands in for what can't be detected. Returns undefined when nothing works;
|
|
2039
|
+
* the overlay then asks.
|
|
1220
2040
|
*/
|
|
1221
2041
|
var ProjectResolver = class {
|
|
1222
2042
|
#memory;
|
|
1223
2043
|
#exec;
|
|
1224
2044
|
#platform;
|
|
2045
|
+
#ensembleForPort;
|
|
1225
2046
|
constructor(options) {
|
|
1226
2047
|
this.#memory = new OriginMemory(join(options.dataDir, "origins.json"));
|
|
1227
2048
|
this.#exec = options.exec ?? defaultExec;
|
|
1228
2049
|
this.#platform = options.platform ?? process.platform;
|
|
2050
|
+
this.#ensembleForPort = options.ensembleForPort;
|
|
1229
2051
|
}
|
|
1230
|
-
async resolve(pageUrl) {
|
|
2052
|
+
async resolve(pageUrl, claimedRoot) {
|
|
1231
2053
|
const origin = safeOrigin(pageUrl);
|
|
1232
2054
|
if (!origin) return void 0;
|
|
1233
|
-
const remembered = await this.#memory.get(origin);
|
|
1234
|
-
if (remembered && existsSync(remembered)) return remembered;
|
|
1235
2055
|
const port = portOf(origin);
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
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;
|
|
1239
2063
|
}
|
|
1240
2064
|
/** Remember the user's choice for an address (from the overlay's project picker). */
|
|
1241
2065
|
remember(pageUrl, root) {
|
|
1242
2066
|
const origin = safeOrigin(pageUrl);
|
|
1243
|
-
return origin ? this.#memory.set(origin,
|
|
2067
|
+
return origin ? this.#memory.set(origin, projectKey(root)) : Promise.resolve();
|
|
1244
2068
|
}
|
|
1245
|
-
/**
|
|
2069
|
+
/**
|
|
2070
|
+
* Folder of the process listening on `port`: its working directory, or its script's
|
|
2071
|
+
* package. When Docker publishes the port, the compose project of the container.
|
|
2072
|
+
*/
|
|
1246
2073
|
async folderForPort(port) {
|
|
1247
|
-
|
|
2074
|
+
const pids = await this.#listeners(port);
|
|
2075
|
+
if (pids.length === 0 && this.#platform === "linux") return this.#composeFolder(port);
|
|
2076
|
+
for (const pid of pids) {
|
|
1248
2077
|
const cwd = await this.#cwd(pid).catch(() => void 0);
|
|
1249
2078
|
if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return cwd;
|
|
1250
|
-
const
|
|
2079
|
+
const commandLine = await this.#commandLine(pid).catch(() => "");
|
|
2080
|
+
if (isDockerForwarder(commandLine)) return this.#composeFolder(port);
|
|
2081
|
+
const fromCommand = projectFromCommandLine(commandLine);
|
|
1251
2082
|
if (fromCommand) return fromCommand;
|
|
1252
2083
|
}
|
|
1253
2084
|
}
|
|
2085
|
+
/** Working directory of the compose project whose container publishes `port`. */
|
|
2086
|
+
async #composeFolder(port) {
|
|
2087
|
+
return firstLine(await this.#exec("docker", [
|
|
2088
|
+
"ps",
|
|
2089
|
+
"--filter",
|
|
2090
|
+
`publish=${port}`,
|
|
2091
|
+
"--format",
|
|
2092
|
+
"{{.Label \"com.docker.compose.project.working_dir\"}}"
|
|
2093
|
+
]).catch(() => ""));
|
|
2094
|
+
}
|
|
1254
2095
|
async #listeners(port) {
|
|
1255
|
-
if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", [
|
|
1256
|
-
"-ano",
|
|
1257
|
-
"-p",
|
|
1258
|
-
"TCP"
|
|
1259
|
-
]), port);
|
|
2096
|
+
if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", ["-ano"]), port);
|
|
1260
2097
|
try {
|
|
1261
2098
|
return parsePids(await this.#exec("lsof", [
|
|
1262
2099
|
"-nP",
|
|
@@ -1295,6 +2132,18 @@ var ProjectResolver = class {
|
|
|
1295
2132
|
]);
|
|
1296
2133
|
}
|
|
1297
2134
|
};
|
|
2135
|
+
/**
|
|
2136
|
+
* A folder with `.git` in it: a checkout, or a worktree (where `.git` is a
|
|
2137
|
+
* file). Any local page can claim a root, so only accept a real repository;
|
|
2138
|
+
* that's the same trust as picking it in the overlay.
|
|
2139
|
+
*/
|
|
2140
|
+
function isGitRoot(folder) {
|
|
2141
|
+
return isAbsolute(folder) && existsSync(join(folder, ".git"));
|
|
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
|
+
}
|
|
1298
2147
|
/** Closest folder with a package.json at or above `folder`, or `folder` itself. */
|
|
1299
2148
|
function projectRoot(folder) {
|
|
1300
2149
|
let dir = resolve(folder);
|
|
@@ -1322,6 +2171,15 @@ function parseNetstat(output, port) {
|
|
|
1322
2171
|
return [...new Set(pids.filter(Number.isInteger))];
|
|
1323
2172
|
}
|
|
1324
2173
|
/**
|
|
2174
|
+
* Processes that forward a published container port to the host: Docker Desktop
|
|
2175
|
+
* (`com.docker.backend`, `vpnkit` before 4.x), Docker Engine on Linux (`docker-proxy`),
|
|
2176
|
+
* OrbStack (`OrbStack Helper`), Colima and Rancher Desktop (`limactl`), Podman (`gvproxy`)
|
|
2177
|
+
* and WSL 2's localhost relay (`wslrelay`).
|
|
2178
|
+
*/
|
|
2179
|
+
function isDockerForwarder(commandLine) {
|
|
2180
|
+
return /(?:^|[\\/"])(?:com\.docker\.backend|vpnkit|docker-proxy|OrbStack Helper|limactl|gvproxy|wslrelay)(?:\.exe)?(?:["\s]|$)/i.test(commandLine.trim());
|
|
2181
|
+
}
|
|
2182
|
+
/**
|
|
1325
2183
|
* Dev servers are started from a project's node_modules
|
|
1326
2184
|
* (`…/eyes/apps/frontend/node_modules/next/dist/bin/next dev`): the part
|
|
1327
2185
|
* before `node_modules` is the project.
|
|
@@ -1329,6 +2187,9 @@ function parseNetstat(output, port) {
|
|
|
1329
2187
|
function projectFromCommandLine(commandLine) {
|
|
1330
2188
|
return commandLine.match(/(?:^|[\s"'])((?:[A-Za-z]:)?[\\/][^\s"']*?)[\\/]node_modules[\\/]/)?.[1];
|
|
1331
2189
|
}
|
|
2190
|
+
function firstLine(output) {
|
|
2191
|
+
return output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
|
|
2192
|
+
}
|
|
1332
2193
|
function safeOrigin(pageUrl) {
|
|
1333
2194
|
try {
|
|
1334
2195
|
return new URL(pageUrl).origin;
|
|
@@ -3257,7 +4118,7 @@ function errorMessage(error) {
|
|
|
3257
4118
|
}
|
|
3258
4119
|
//#endregion
|
|
3259
4120
|
//#region src/version.ts
|
|
3260
|
-
const VERSION = "0.
|
|
4121
|
+
const VERSION = "0.9.0";
|
|
3261
4122
|
//#endregion
|
|
3262
4123
|
//#region src/daemon/thread-store.ts
|
|
3263
4124
|
const StoreFile = z.object({
|
|
@@ -3276,7 +4137,7 @@ function defaultDataDir() {
|
|
|
3276
4137
|
* shared between two bridges.
|
|
3277
4138
|
*/
|
|
3278
4139
|
function projectStorePath(projectRoot, dataDir = defaultDataDir()) {
|
|
3279
|
-
const root =
|
|
4140
|
+
const root = projectKey(projectRoot);
|
|
3280
4141
|
const hash = createHash("sha256").update(root).digest("hex").slice(0, 10);
|
|
3281
4142
|
const slug = basename(root).replace(/[^a-z0-9._-]+/gi, "-").slice(0, 40) || "project";
|
|
3282
4143
|
return join(dataDir, "projects", `${slug}-${hash}.json`);
|
|
@@ -3292,7 +4153,7 @@ var FileThreadStore = class {
|
|
|
3292
4153
|
#writeTimer;
|
|
3293
4154
|
#writing = Promise.resolve();
|
|
3294
4155
|
constructor(projectRoot, dataDir) {
|
|
3295
|
-
this.#root =
|
|
4156
|
+
this.#root = projectKey(projectRoot);
|
|
3296
4157
|
this.path = projectStorePath(this.#root, dataDir);
|
|
3297
4158
|
}
|
|
3298
4159
|
async load() {
|
|
@@ -3351,14 +4212,25 @@ var FileThreadStore = class {
|
|
|
3351
4212
|
};
|
|
3352
4213
|
//#endregion
|
|
3353
4214
|
//#region src/daemon/agents.ts
|
|
3354
|
-
const PROVIDERS = [
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
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
|
+
];
|
|
3362
4234
|
const providerLabel = (id) => PROVIDER_OPTIONS.find((option) => option.id === id)?.label ?? id;
|
|
3363
4235
|
const SettingsFile$1 = z.object({
|
|
3364
4236
|
version: z.literal(1),
|
|
@@ -3386,23 +4258,33 @@ async function saveProvider(provider, dataDir = defaultDataDir()) {
|
|
|
3386
4258
|
}, null, 2)}\n`);
|
|
3387
4259
|
await rename(`${path}.tmp`, path);
|
|
3388
4260
|
}
|
|
3389
|
-
/**
|
|
4261
|
+
/**
|
|
4262
|
+
* Which agents this machine has: a paired or running T3 Code, an installed
|
|
4263
|
+
* Claude Code, a running Ensemble app.
|
|
4264
|
+
*/
|
|
3390
4265
|
async function detectAgents(options = {}) {
|
|
3391
|
-
const [t3code, claudeCode] = await Promise.all([
|
|
4266
|
+
const [t3code, claudeCode, ensemble] = await Promise.all([
|
|
4267
|
+
hasT3Code(options.t3Url),
|
|
4268
|
+
hasClaudeCode(),
|
|
4269
|
+
hasEnsemble()
|
|
4270
|
+
]);
|
|
3392
4271
|
return {
|
|
3393
4272
|
t3code,
|
|
3394
|
-
"claude-code": claudeCode
|
|
4273
|
+
"claude-code": claudeCode,
|
|
4274
|
+
ensemble
|
|
3395
4275
|
};
|
|
3396
4276
|
}
|
|
3397
4277
|
/**
|
|
3398
4278
|
* The agent for projects that haven't picked one: the saved choice, else the
|
|
3399
|
-
*
|
|
4279
|
+
* first agent found (T3 Code, Claude Code, Ensemble), else T3 Code.
|
|
3400
4280
|
*/
|
|
3401
4281
|
async function machineProvider(options = {}) {
|
|
3402
4282
|
const saved = await savedProvider(options.dataDir);
|
|
3403
4283
|
if (saved) return saved;
|
|
3404
4284
|
const found = await detectAgents(options);
|
|
3405
|
-
|
|
4285
|
+
if (found.t3code) return "t3code";
|
|
4286
|
+
if (found["claude-code"]) return "claude-code";
|
|
4287
|
+
return found.ensemble ? "ensemble" : "t3code";
|
|
3406
4288
|
}
|
|
3407
4289
|
async function hasT3Code(t3Url) {
|
|
3408
4290
|
const store = new CredentialStore();
|
|
@@ -3414,6 +4296,10 @@ async function hasT3Code(t3Url) {
|
|
|
3414
4296
|
return false;
|
|
3415
4297
|
}
|
|
3416
4298
|
}
|
|
4299
|
+
/** Ensemble's app, running now; finding it needs no token. */
|
|
4300
|
+
function hasEnsemble() {
|
|
4301
|
+
return new EnsembleClient().isRunning();
|
|
4302
|
+
}
|
|
3417
4303
|
/** `claude` on the PATH, or its config folder (login services get a bare PATH). */
|
|
3418
4304
|
async function hasClaudeCode() {
|
|
3419
4305
|
const names = process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"];
|
|
@@ -3514,6 +4400,801 @@ function isLoopbackAddress(address) {
|
|
|
3514
4400
|
return ip === "::1" || /^127(?:\.\d{1,3}){3}$/.test(ip);
|
|
3515
4401
|
}
|
|
3516
4402
|
//#endregion
|
|
4403
|
+
//#region src/service/daemon-command.ts
|
|
4404
|
+
function daemonArgs(command) {
|
|
4405
|
+
return [
|
|
4406
|
+
command.cli,
|
|
4407
|
+
"daemon",
|
|
4408
|
+
"--port",
|
|
4409
|
+
String(command.port),
|
|
4410
|
+
...command.args ?? []
|
|
4411
|
+
];
|
|
4412
|
+
}
|
|
4413
|
+
//#endregion
|
|
4414
|
+
//#region src/service/versions.ts
|
|
4415
|
+
/** Compare dotted versions by number (pre-release tags ignored): below 0, 0 or above 0. */
|
|
4416
|
+
function compareVersions(a, b) {
|
|
4417
|
+
const parts = (version) => version.split("-")[0]?.split(".").map(Number) ?? [];
|
|
4418
|
+
const [left, right] = [parts(a), parts(b)];
|
|
4419
|
+
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
4420
|
+
const difference = (left[i] ?? 0) - (right[i] ?? 0);
|
|
4421
|
+
if (difference) return difference;
|
|
4422
|
+
}
|
|
4423
|
+
return 0;
|
|
4424
|
+
}
|
|
4425
|
+
/**
|
|
4426
|
+
* npx reuses what it cached for `npx tencil`, so an older Tencil can run after
|
|
4427
|
+
* a newer one was set up. It must never replace that newer daemon.
|
|
4428
|
+
*/
|
|
4429
|
+
function isNewerThanThis(version) {
|
|
4430
|
+
return version !== void 0 && compareVersions(version, VERSION) > 0;
|
|
4431
|
+
}
|
|
4432
|
+
var NewerDaemonError = class extends Error {
|
|
4433
|
+
constructor(running) {
|
|
4434
|
+
super(`Tencil ${running} is already running and this is ${VERSION}, which is older. Run \`npx tencil@latest\` instead.`);
|
|
4435
|
+
this.name = "NewerDaemonError";
|
|
4436
|
+
}
|
|
4437
|
+
};
|
|
4438
|
+
const DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
4439
|
+
/** Where to look Tencil up: npm, or `TENCIL_REGISTRY_URL` (a mirror, a test registry). */
|
|
4440
|
+
function registryUrl(env = process.env) {
|
|
4441
|
+
return (env.TENCIL_REGISTRY_URL || DEFAULT_REGISTRY).replace(/\/+$/, "");
|
|
4442
|
+
}
|
|
4443
|
+
/**
|
|
4444
|
+
* Machines that shouldn't phone home: `TENCIL_NO_UPDATE_CHECK` is set, or
|
|
4445
|
+
* it's CI. Neither the CLI nor the daemon asks the registry then.
|
|
4446
|
+
*/
|
|
4447
|
+
function updateChecksDisabled(env = process.env) {
|
|
4448
|
+
const set = (value) => value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
4449
|
+
return set(env.TENCIL_NO_UPDATE_CHECK) || set(env.CI);
|
|
4450
|
+
}
|
|
4451
|
+
/** The newest published Tencil, or undefined when the registry doesn't answer quickly. */
|
|
4452
|
+
async function latestVersion(options = {}) {
|
|
4453
|
+
const response = await fetch(`${options.registry ?? registryUrl()}/tencil/latest`, { signal: AbortSignal.timeout(options.timeoutMs ?? 1500) }).catch(() => void 0);
|
|
4454
|
+
if (!response?.ok) return void 0;
|
|
4455
|
+
const body = await response.json().catch(() => void 0);
|
|
4456
|
+
return typeof body?.version === "string" ? body.version : void 0;
|
|
4457
|
+
}
|
|
4458
|
+
/** A one-line nudge when a newer Tencil is published. */
|
|
4459
|
+
async function updateNotice() {
|
|
4460
|
+
if (updateChecksDisabled()) return void 0;
|
|
4461
|
+
const latest = await latestVersion();
|
|
4462
|
+
return latest && isNewerThanThis(latest) ? `Tencil ${latest} is out (this is ${VERSION}): npx tencil@latest` : void 0;
|
|
4463
|
+
}
|
|
4464
|
+
//#endregion
|
|
4465
|
+
//#region src/service/background.ts
|
|
4466
|
+
/**
|
|
4467
|
+
* Start the daemon in the background unless it already runs. A daemon from an
|
|
4468
|
+
* older Tencil version is replaced so pages always get the current overlay;
|
|
4469
|
+
* so is one running with other flags than the ones given. Without flags of
|
|
4470
|
+
* its own, a replacement keeps the running daemon's (`--listen`, `--t3-url`, …).
|
|
4471
|
+
*/
|
|
4472
|
+
async function startInBackground(command, dataDir) {
|
|
4473
|
+
const running = await probeDaemon(command.port);
|
|
4474
|
+
if (running && isNewerThanThis(running.version)) return {
|
|
4475
|
+
status: "running",
|
|
4476
|
+
pid: running.pid,
|
|
4477
|
+
newer: running.version
|
|
4478
|
+
};
|
|
4479
|
+
const flags = command.args?.length ? command.args : running?.flags ?? [];
|
|
4480
|
+
if (running && running.version === VERSION && sameFlags(running.flags, flags)) return {
|
|
4481
|
+
status: "running",
|
|
4482
|
+
pid: running.pid
|
|
4483
|
+
};
|
|
4484
|
+
if (running) await stopDaemon(command.port);
|
|
4485
|
+
spawnDaemon({
|
|
4486
|
+
...command,
|
|
4487
|
+
args: flags
|
|
4488
|
+
}, dataDir);
|
|
4489
|
+
const health = await waitForDaemon(command.port, dataDir);
|
|
4490
|
+
return {
|
|
4491
|
+
status: running ? "restarted" : "started",
|
|
4492
|
+
pid: health.pid
|
|
4493
|
+
};
|
|
4494
|
+
}
|
|
4495
|
+
/** Launch the daemon detached, logging to daemon.log. Doesn't wait for it. */
|
|
4496
|
+
function spawnDaemon(command, dataDir) {
|
|
4497
|
+
mkdirSync(dataDir, { recursive: true });
|
|
4498
|
+
const logFile = openSync(join(dataDir, "daemon.log"), "a");
|
|
4499
|
+
spawn(command.node, daemonArgs(command), {
|
|
4500
|
+
detached: true,
|
|
4501
|
+
stdio: [
|
|
4502
|
+
"ignore",
|
|
4503
|
+
logFile,
|
|
4504
|
+
logFile
|
|
4505
|
+
],
|
|
4506
|
+
windowsHide: true
|
|
4507
|
+
}).unref();
|
|
4508
|
+
}
|
|
4509
|
+
/** Wait for a daemon on `port` (optionally one of `version`) to answer. */
|
|
4510
|
+
async function waitForDaemon(port, dataDir, version, attempts = 100) {
|
|
4511
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
4512
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
4513
|
+
const health = await probeDaemon(port);
|
|
4514
|
+
if (health && (!version || health.version === version)) return health;
|
|
4515
|
+
}
|
|
4516
|
+
throw new Error(`The daemon didn't start. See ${join(dataDir, "daemon.log")}.`);
|
|
4517
|
+
}
|
|
4518
|
+
function sameFlags(a, b) {
|
|
4519
|
+
return a.length === b.length && a.every((flag, i) => flag === b[i]);
|
|
4520
|
+
}
|
|
4521
|
+
/** Stop the daemon answering on `port`. Returns false when none was running. */
|
|
4522
|
+
async function stopDaemon(port = DEFAULT_PORT) {
|
|
4523
|
+
const running = await probeDaemon(port);
|
|
4524
|
+
if (!running) return false;
|
|
4525
|
+
try {
|
|
4526
|
+
process.kill(running.pid, "SIGTERM");
|
|
4527
|
+
} catch {
|
|
4528
|
+
return false;
|
|
4529
|
+
}
|
|
4530
|
+
for (let attempt = 0; attempt < 50; attempt++) {
|
|
4531
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
4532
|
+
if (!await probeDaemon(port)) return true;
|
|
4533
|
+
}
|
|
4534
|
+
return true;
|
|
4535
|
+
}
|
|
4536
|
+
//#endregion
|
|
4537
|
+
//#region src/service/login-service.ts
|
|
4538
|
+
function serviceNames(port = DEFAULT_PORT) {
|
|
4539
|
+
const own = port !== DEFAULT_PORT;
|
|
4540
|
+
return {
|
|
4541
|
+
label: own ? `dev.tencil.daemon.${port}` : "dev.tencil.daemon",
|
|
4542
|
+
unit: own ? `tencil-${port}.service` : "tencil.service",
|
|
4543
|
+
task: own ? `Tencil ${port}` : "Tencil"
|
|
4544
|
+
};
|
|
4545
|
+
}
|
|
4546
|
+
/**
|
|
4547
|
+
* What the daemon needs from the shell that installed it. launchd and systemd
|
|
4548
|
+
* start it with a bare PATH (`/usr/bin:/bin`), where nvm's npm and npx, which
|
|
4549
|
+
* it runs to pair and to install the Claude Agent SDK, can't be found; and a
|
|
4550
|
+
* custom XDG_CONFIG_HOME must reach it, or it reads another data folder than
|
|
4551
|
+
* the CLI. npx's and npm's own folders (anything in node_modules) are left out of PATH.
|
|
4552
|
+
*/
|
|
4553
|
+
function serviceEnvironment(command, env = process.env) {
|
|
4554
|
+
const separator = process.platform === "win32" ? ";" : ":";
|
|
4555
|
+
const entries = [dirname(command.node), ...(env.PATH ?? "").split(separator)].filter((entry) => entry && !/[\\/](?:_npx|node_modules)[\\/]/.test(entry));
|
|
4556
|
+
const environment = { PATH: [...new Set(entries)].join(separator) };
|
|
4557
|
+
if (env.XDG_CONFIG_HOME) environment.XDG_CONFIG_HOME = env.XDG_CONFIG_HOME;
|
|
4558
|
+
return environment;
|
|
4559
|
+
}
|
|
4560
|
+
function launchdPlist(command, logPath, environment = {}) {
|
|
4561
|
+
const args = [command.node, ...daemonArgs(command)].map((arg) => ` <string>${escapeXml(arg)}</string>`).join("\n");
|
|
4562
|
+
const variables = Object.entries(environment).map(([key, value]) => ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`).join("\n");
|
|
4563
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
4564
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
4565
|
+
<plist version="1.0">
|
|
4566
|
+
<dict>
|
|
4567
|
+
<key>Label</key>
|
|
4568
|
+
<string>${serviceNames(command.port).label}</string>
|
|
4569
|
+
<key>ProgramArguments</key>
|
|
4570
|
+
<array>
|
|
4571
|
+
${args}
|
|
4572
|
+
</array>
|
|
4573
|
+
<key>EnvironmentVariables</key>
|
|
4574
|
+
<dict>
|
|
4575
|
+
${variables}
|
|
4576
|
+
</dict>
|
|
4577
|
+
<key>RunAtLoad</key>
|
|
4578
|
+
<true/>
|
|
4579
|
+
<key>KeepAlive</key>
|
|
4580
|
+
<true/>
|
|
4581
|
+
<key>StandardOutPath</key>
|
|
4582
|
+
<string>${escapeXml(logPath)}</string>
|
|
4583
|
+
<key>StandardErrorPath</key>
|
|
4584
|
+
<string>${escapeXml(logPath)}</string>
|
|
4585
|
+
</dict>
|
|
4586
|
+
</plist>
|
|
4587
|
+
`;
|
|
4588
|
+
}
|
|
4589
|
+
function systemdUnit(command, environment = {}) {
|
|
4590
|
+
return `[Unit]
|
|
4591
|
+
Description=Tencil daemon
|
|
4592
|
+
|
|
4593
|
+
[Service]
|
|
4594
|
+
${Object.entries(environment).map(([key, value]) => `Environment="${key}=${value}"\n`).join("")}ExecStart=${[command.node, ...daemonArgs(command)].map((arg) => `"${arg}"`).join(" ")}
|
|
4595
|
+
Restart=on-failure
|
|
4596
|
+
|
|
4597
|
+
[Install]
|
|
4598
|
+
WantedBy=default.target
|
|
4599
|
+
`;
|
|
4600
|
+
}
|
|
4601
|
+
function windowsTaskCommand(command) {
|
|
4602
|
+
return [command.node, ...daemonArgs(command)].map((arg) => `"${arg}"`).join(" ");
|
|
4603
|
+
}
|
|
4604
|
+
const launchAgent = (names) => join(homedir(), "Library", "LaunchAgents", `${names.label}.plist`);
|
|
4605
|
+
const systemdUnitPath = (names) => join(homedir(), ".config", "systemd", "user", names.unit);
|
|
4606
|
+
const launchdDomain = () => `gui/${process.getuid?.() ?? 501}`;
|
|
4607
|
+
/** Whether Tencil is set up to start at login, serving `port`. */
|
|
4608
|
+
function isServiceInstalled(port = DEFAULT_PORT) {
|
|
4609
|
+
return servicePort(readServiceDefinition(serviceNames(port))) === port;
|
|
4610
|
+
}
|
|
4611
|
+
/** The daemon port in a launchd plist, systemd unit or scheduled task definition. */
|
|
4612
|
+
function servicePort(definition) {
|
|
4613
|
+
const match = definition?.match(/--port(?:<\/string>\s*<string>|"?\s+"?|"\s*")(\d+)/);
|
|
4614
|
+
return match?.[1] ? Number(match[1]) : void 0;
|
|
4615
|
+
}
|
|
4616
|
+
/** The launchd plist, systemd unit or scheduled task behind `names`, if installed. */
|
|
4617
|
+
function readServiceDefinition(names) {
|
|
4618
|
+
try {
|
|
4619
|
+
switch (process.platform) {
|
|
4620
|
+
case "darwin": return readFileSync(launchAgent(names), "utf8");
|
|
4621
|
+
case "linux": return readFileSync(systemdUnitPath(names), "utf8");
|
|
4622
|
+
case "win32": return execFileSync("schtasks", [
|
|
4623
|
+
"/Query",
|
|
4624
|
+
"/TN",
|
|
4625
|
+
names.task,
|
|
4626
|
+
"/XML"
|
|
4627
|
+
], {
|
|
4628
|
+
encoding: "utf8",
|
|
4629
|
+
stdio: [
|
|
4630
|
+
"ignore",
|
|
4631
|
+
"pipe",
|
|
4632
|
+
"ignore"
|
|
4633
|
+
]
|
|
4634
|
+
});
|
|
4635
|
+
default: return;
|
|
4636
|
+
}
|
|
4637
|
+
} catch {
|
|
4638
|
+
return;
|
|
4639
|
+
}
|
|
4640
|
+
}
|
|
4641
|
+
/** Install (or replace) the login service and start the daemon through it. */
|
|
4642
|
+
async function installService(command, dataDir) {
|
|
4643
|
+
const logPath = join(dataDir, "daemon.log");
|
|
4644
|
+
const names = serviceNames(command.port);
|
|
4645
|
+
const { unit: unitName, task } = names;
|
|
4646
|
+
mkdirSync(dataDir, { recursive: true });
|
|
4647
|
+
switch (process.platform) {
|
|
4648
|
+
case "darwin": {
|
|
4649
|
+
const plist = launchAgent(names);
|
|
4650
|
+
quietly("launchctl", [
|
|
4651
|
+
"bootout",
|
|
4652
|
+
launchdDomain(),
|
|
4653
|
+
plist
|
|
4654
|
+
]);
|
|
4655
|
+
await stopDaemon(command.port);
|
|
4656
|
+
mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
|
|
4657
|
+
writeFileSync(plist, launchdPlist(command, logPath, serviceEnvironment(command)));
|
|
4658
|
+
execFileSync("launchctl", [
|
|
4659
|
+
"bootstrap",
|
|
4660
|
+
launchdDomain(),
|
|
4661
|
+
plist
|
|
4662
|
+
]);
|
|
4663
|
+
return plist;
|
|
4664
|
+
}
|
|
4665
|
+
case "linux": {
|
|
4666
|
+
const unit = systemdUnitPath(names);
|
|
4667
|
+
quietly("systemctl", [
|
|
4668
|
+
"--user",
|
|
4669
|
+
"stop",
|
|
4670
|
+
unitName
|
|
4671
|
+
]);
|
|
4672
|
+
await stopDaemon(command.port);
|
|
4673
|
+
mkdirSync(join(homedir(), ".config", "systemd", "user"), { recursive: true });
|
|
4674
|
+
writeFileSync(unit, systemdUnit(command, serviceEnvironment(command)));
|
|
4675
|
+
execFileSync("systemctl", ["--user", "daemon-reload"]);
|
|
4676
|
+
execFileSync("systemctl", [
|
|
4677
|
+
"--user",
|
|
4678
|
+
"enable",
|
|
4679
|
+
"--now",
|
|
4680
|
+
unitName
|
|
4681
|
+
], { stdio: [
|
|
4682
|
+
"ignore",
|
|
4683
|
+
"ignore",
|
|
4684
|
+
"pipe"
|
|
4685
|
+
] });
|
|
4686
|
+
return unit;
|
|
4687
|
+
}
|
|
4688
|
+
case "win32":
|
|
4689
|
+
quietly("schtasks", [
|
|
4690
|
+
"/End",
|
|
4691
|
+
"/TN",
|
|
4692
|
+
task
|
|
4693
|
+
]);
|
|
4694
|
+
await stopDaemon(command.port);
|
|
4695
|
+
execFileSync("schtasks", [
|
|
4696
|
+
"/Create",
|
|
4697
|
+
"/F",
|
|
4698
|
+
"/SC",
|
|
4699
|
+
"ONLOGON",
|
|
4700
|
+
"/TN",
|
|
4701
|
+
task,
|
|
4702
|
+
"/TR",
|
|
4703
|
+
windowsTaskCommand(command)
|
|
4704
|
+
]);
|
|
4705
|
+
execFileSync("schtasks", [
|
|
4706
|
+
"/Run",
|
|
4707
|
+
"/TN",
|
|
4708
|
+
task
|
|
4709
|
+
]);
|
|
4710
|
+
return `Task Scheduler: ${task}`;
|
|
4711
|
+
default: throw new Error(`Login service isn't supported on ${process.platform}; use \`tencil start\`.`);
|
|
4712
|
+
}
|
|
4713
|
+
}
|
|
4714
|
+
/** Stop the service's daemon until the next login, without uninstalling it. */
|
|
4715
|
+
async function stopService(port = DEFAULT_PORT) {
|
|
4716
|
+
const names = serviceNames(port);
|
|
4717
|
+
const { unit, task } = names;
|
|
4718
|
+
switch (process.platform) {
|
|
4719
|
+
case "darwin":
|
|
4720
|
+
quietly("launchctl", [
|
|
4721
|
+
"bootout",
|
|
4722
|
+
launchdDomain(),
|
|
4723
|
+
launchAgent(names)
|
|
4724
|
+
]);
|
|
4725
|
+
break;
|
|
4726
|
+
case "linux":
|
|
4727
|
+
quietly("systemctl", [
|
|
4728
|
+
"--user",
|
|
4729
|
+
"stop",
|
|
4730
|
+
unit
|
|
4731
|
+
]);
|
|
4732
|
+
break;
|
|
4733
|
+
case "win32": quietly("schtasks", [
|
|
4734
|
+
"/End",
|
|
4735
|
+
"/TN",
|
|
4736
|
+
task
|
|
4737
|
+
]);
|
|
4738
|
+
}
|
|
4739
|
+
await stopDaemon(port);
|
|
4740
|
+
}
|
|
4741
|
+
async function uninstallService(port = DEFAULT_PORT) {
|
|
4742
|
+
removeService(serviceNames(port));
|
|
4743
|
+
await stopDaemon(port);
|
|
4744
|
+
}
|
|
4745
|
+
/** Unload and delete the service behind `names`, wherever it is in its life. */
|
|
4746
|
+
function removeService(names) {
|
|
4747
|
+
switch (process.platform) {
|
|
4748
|
+
case "darwin":
|
|
4749
|
+
quietly("launchctl", [
|
|
4750
|
+
"bootout",
|
|
4751
|
+
launchdDomain(),
|
|
4752
|
+
launchAgent(names)
|
|
4753
|
+
]);
|
|
4754
|
+
rmSync(launchAgent(names), { force: true });
|
|
4755
|
+
break;
|
|
4756
|
+
case "linux":
|
|
4757
|
+
quietly("systemctl", [
|
|
4758
|
+
"--user",
|
|
4759
|
+
"disable",
|
|
4760
|
+
"--now",
|
|
4761
|
+
names.unit
|
|
4762
|
+
]);
|
|
4763
|
+
rmSync(systemdUnitPath(names), { force: true });
|
|
4764
|
+
quietly("systemctl", ["--user", "daemon-reload"]);
|
|
4765
|
+
break;
|
|
4766
|
+
case "win32":
|
|
4767
|
+
quietly("schtasks", [
|
|
4768
|
+
"/End",
|
|
4769
|
+
"/TN",
|
|
4770
|
+
names.task
|
|
4771
|
+
]);
|
|
4772
|
+
quietly("schtasks", [
|
|
4773
|
+
"/Delete",
|
|
4774
|
+
"/F",
|
|
4775
|
+
"/TN",
|
|
4776
|
+
names.task
|
|
4777
|
+
]);
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
/** Run a command whose failure only means "nothing to do" (not loaded, already gone). */
|
|
4781
|
+
function quietly(command, args) {
|
|
4782
|
+
try {
|
|
4783
|
+
execFileSync(command, args, { stdio: "ignore" });
|
|
4784
|
+
} catch {}
|
|
4785
|
+
}
|
|
4786
|
+
function escapeXml(value) {
|
|
4787
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
4788
|
+
}
|
|
4789
|
+
//#endregion
|
|
4790
|
+
//#region src/service/autostart.ts
|
|
4791
|
+
/**
|
|
4792
|
+
* Running from a package manager's install (npx's cache, a project, a global
|
|
4793
|
+
* prefix) rather than a source checkout. Those can be cleaned up or upgraded
|
|
4794
|
+
* under a login service, so it gets its own copy.
|
|
4795
|
+
*/
|
|
4796
|
+
function isPackageInstall(cliPath) {
|
|
4797
|
+
return /[\\/]node_modules[\\/]/.test(cliPath);
|
|
4798
|
+
}
|
|
4799
|
+
/** The login service's own copy of Tencil; one per port, like the service. */
|
|
4800
|
+
function runtimeDir(dataDir, port = DEFAULT_PORT) {
|
|
4801
|
+
return join(dataDir, port === 4747 ? "runtime" : `runtime-${port}`);
|
|
4802
|
+
}
|
|
4803
|
+
function runtimeCli(dataDir, port = DEFAULT_PORT) {
|
|
4804
|
+
return cliIn(runtimeDir(dataDir, port));
|
|
4805
|
+
}
|
|
4806
|
+
/** The CLI of a Tencil installed with `npm install --prefix dir`. */
|
|
4807
|
+
function cliIn(dir) {
|
|
4808
|
+
return join(dir, "node_modules", "tencil", "dist", "cli.mjs");
|
|
4809
|
+
}
|
|
4810
|
+
function runtimeInstallArgs(dataDir, spec, port = DEFAULT_PORT) {
|
|
4811
|
+
return installArgs(runtimeDir(dataDir, port), spec);
|
|
4812
|
+
}
|
|
4813
|
+
function installArgs(dir, spec) {
|
|
4814
|
+
const registry = process.env.TENCIL_REGISTRY_URL;
|
|
4815
|
+
return [
|
|
4816
|
+
"install",
|
|
4817
|
+
"--prefix",
|
|
4818
|
+
dir,
|
|
4819
|
+
spec,
|
|
4820
|
+
"--no-audit",
|
|
4821
|
+
"--no-fund",
|
|
4822
|
+
"--loglevel=error",
|
|
4823
|
+
...registry ? ["--registry", registry] : []
|
|
4824
|
+
];
|
|
4825
|
+
}
|
|
4826
|
+
/**
|
|
4827
|
+
* Start Tencil at login and now. Keeps the running daemon's flags unless new
|
|
4828
|
+
* ones are given. `from` installs another package spec (a local tarball) as
|
|
4829
|
+
* the service's copy instead of this version from npm.
|
|
4830
|
+
*/
|
|
4831
|
+
async function enableAutostart(command, dataDir, from) {
|
|
4832
|
+
const running = await probeDaemon(command.port);
|
|
4833
|
+
if (running && isNewerThanThis(running.version)) throw new NewerDaemonError(running.version);
|
|
4834
|
+
const args = command.args?.length ? command.args : running?.flags ?? [];
|
|
4835
|
+
let cli = command.cli;
|
|
4836
|
+
if (isPackageInstall(cli)) {
|
|
4837
|
+
const spec = from && existsSync(from) ? resolve(from) : from ?? `tencil@${VERSION}`;
|
|
4838
|
+
const result = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", runtimeInstallArgs(dataDir, spec, command.port), {
|
|
4839
|
+
encoding: "utf8",
|
|
4840
|
+
stdio: [
|
|
4841
|
+
"ignore",
|
|
4842
|
+
"ignore",
|
|
4843
|
+
"pipe"
|
|
4844
|
+
],
|
|
4845
|
+
shell: process.platform === "win32",
|
|
4846
|
+
env: withoutNpmEnv()
|
|
4847
|
+
});
|
|
4848
|
+
if (result.status !== 0) throw new Error(`Couldn't install Tencil for the login service (npm ${result.status ?? "failed"}): ${result.stderr?.trim() ?? ""}`);
|
|
4849
|
+
cli = runtimeCli(dataDir, command.port);
|
|
4850
|
+
}
|
|
4851
|
+
const where = await installService({
|
|
4852
|
+
...command,
|
|
4853
|
+
cli,
|
|
4854
|
+
args
|
|
4855
|
+
}, dataDir);
|
|
4856
|
+
await waitForDaemon(command.port, dataDir);
|
|
4857
|
+
return where;
|
|
4858
|
+
}
|
|
4859
|
+
/**
|
|
4860
|
+
* Make sure this version of the daemon runs. With a login service it is
|
|
4861
|
+
* updated in place, since stopping its daemon would only make it restart.
|
|
4862
|
+
*/
|
|
4863
|
+
async function ensureDaemon(command, dataDir) {
|
|
4864
|
+
if (!isServiceInstalled(command.port)) {
|
|
4865
|
+
const { status, newer } = await startInBackground(command, dataDir);
|
|
4866
|
+
return {
|
|
4867
|
+
status,
|
|
4868
|
+
autostart: false,
|
|
4869
|
+
newer
|
|
4870
|
+
};
|
|
4871
|
+
}
|
|
4872
|
+
const running = await probeDaemon(command.port);
|
|
4873
|
+
if (running && isNewerThanThis(running.version)) return {
|
|
4874
|
+
status: "running",
|
|
4875
|
+
autostart: true,
|
|
4876
|
+
newer: running.version
|
|
4877
|
+
};
|
|
4878
|
+
const flags = command.args?.length ? command.args : running?.flags ?? [];
|
|
4879
|
+
if (running && running.version === VERSION && sameFlags(running.flags, flags)) return {
|
|
4880
|
+
status: "running",
|
|
4881
|
+
autostart: true
|
|
4882
|
+
};
|
|
4883
|
+
await enableAutostart(command, dataDir);
|
|
4884
|
+
return {
|
|
4885
|
+
status: running ? "restarted" : "started",
|
|
4886
|
+
autostart: true
|
|
4887
|
+
};
|
|
4888
|
+
}
|
|
4889
|
+
//#endregion
|
|
4890
|
+
//#region src/service/self-update.ts
|
|
4891
|
+
/**
|
|
4892
|
+
* Updating from the overlay. The daemon installs the new version next to the
|
|
4893
|
+
* runtime (`runtime.next`), then hands off to a helper process, since a
|
|
4894
|
+
* login service's daemon can't restart itself: stopping it ends the
|
|
4895
|
+
* service. The helper swaps the copies, restarts the daemon on the new one
|
|
4896
|
+
* and keeps the old copy (`runtime.previous`) until the new daemon answers.
|
|
4897
|
+
* If it doesn't, the old copy goes back and the old daemon is restarted.
|
|
4898
|
+
*/
|
|
4899
|
+
function stagingDir(dataDir, port) {
|
|
4900
|
+
return `${runtimeDir(dataDir, port)}.next`;
|
|
4901
|
+
}
|
|
4902
|
+
function previousDir(dataDir, port) {
|
|
4903
|
+
return `${runtimeDir(dataDir, port)}.previous`;
|
|
4904
|
+
}
|
|
4905
|
+
/** Why the last update was rolled back, for the restarted old daemon to report. */
|
|
4906
|
+
function failureFile(dataDir, port) {
|
|
4907
|
+
return `${runtimeDir(dataDir, port)}.failed.json`;
|
|
4908
|
+
}
|
|
4909
|
+
function planFile(dataDir, port) {
|
|
4910
|
+
return `${runtimeDir(dataDir, port)}.update.json`;
|
|
4911
|
+
}
|
|
4912
|
+
/** The setup way (`runtimeInstallArgs`), without blocking the daemon while npm runs. */
|
|
4913
|
+
const npmInstall = (spec, dir) => new Promise((resolve, reject) => {
|
|
4914
|
+
const child = spawn(process.platform === "win32" ? "npm.cmd" : "npm", installArgs(dir, spec), {
|
|
4915
|
+
stdio: [
|
|
4916
|
+
"ignore",
|
|
4917
|
+
"ignore",
|
|
4918
|
+
"pipe"
|
|
4919
|
+
],
|
|
4920
|
+
shell: process.platform === "win32",
|
|
4921
|
+
env: withoutNpmEnv(),
|
|
4922
|
+
windowsHide: true
|
|
4923
|
+
});
|
|
4924
|
+
let stderr = "";
|
|
4925
|
+
child.stderr?.on("data", (chunk) => {
|
|
4926
|
+
stderr = (stderr + String(chunk)).slice(-2e3);
|
|
4927
|
+
});
|
|
4928
|
+
const timer = setTimeout(() => child.kill(), 3e5);
|
|
4929
|
+
child.once("error", (error) => {
|
|
4930
|
+
clearTimeout(timer);
|
|
4931
|
+
reject(error);
|
|
4932
|
+
});
|
|
4933
|
+
child.once("close", (code) => {
|
|
4934
|
+
clearTimeout(timer);
|
|
4935
|
+
if (code === 0) return resolve();
|
|
4936
|
+
const lines = stderr.trim().split("\n").slice(-3).join(" ");
|
|
4937
|
+
reject(/* @__PURE__ */ new Error(`npm install failed (${code ?? "killed"})${lines ? `: ${lines}` : ""}`));
|
|
4938
|
+
});
|
|
4939
|
+
});
|
|
4940
|
+
/** Install `version` into the staging folder. Returns its CLI. */
|
|
4941
|
+
async function stageUpdate(version, options) {
|
|
4942
|
+
const dir = stagingDir(options.dataDir, options.port);
|
|
4943
|
+
rmSync(dir, {
|
|
4944
|
+
recursive: true,
|
|
4945
|
+
force: true
|
|
4946
|
+
});
|
|
4947
|
+
mkdirSync(dir, { recursive: true });
|
|
4948
|
+
await (options.install ?? npmInstall)(`tencil@${version}`, dir);
|
|
4949
|
+
const installed = installedVersion(dir);
|
|
4950
|
+
if (installed !== version) {
|
|
4951
|
+
rmSync(dir, {
|
|
4952
|
+
recursive: true,
|
|
4953
|
+
force: true
|
|
4954
|
+
});
|
|
4955
|
+
throw new Error(`Installed ${installed ? `Tencil ${installed}` : "nothing"}, not ${version}`);
|
|
4956
|
+
}
|
|
4957
|
+
return cliIn(dir);
|
|
4958
|
+
}
|
|
4959
|
+
function installedVersion(dir) {
|
|
4960
|
+
try {
|
|
4961
|
+
const pkg = JSON.parse(readFileSync(join(dir, "node_modules", "tencil", "package.json"), "utf8"));
|
|
4962
|
+
return existsSync(cliIn(dir)) ? pkg.version : void 0;
|
|
4963
|
+
} catch {
|
|
4964
|
+
return;
|
|
4965
|
+
}
|
|
4966
|
+
}
|
|
4967
|
+
/**
|
|
4968
|
+
* Start the helper (`tencil finish-update`) from `cli`, detached so it
|
|
4969
|
+
* outlives this daemon. On Linux a service's processes all stop with it,
|
|
4970
|
+
* so the helper gets its own scope there.
|
|
4971
|
+
*/
|
|
4972
|
+
function handOffUpdate(plan, cli) {
|
|
4973
|
+
const file = planFile(plan.dataDir, plan.port);
|
|
4974
|
+
writeFileSync(file, JSON.stringify(plan, null, 2));
|
|
4975
|
+
const args = [
|
|
4976
|
+
cli,
|
|
4977
|
+
"finish-update",
|
|
4978
|
+
file
|
|
4979
|
+
];
|
|
4980
|
+
const scoped = process.platform === "linux" && isServiceInstalled(plan.port) && spawnSync("systemd-run", ["--version"], { stdio: "ignore" }).status === 0;
|
|
4981
|
+
const logFile = openSync(join(plan.dataDir, "daemon.log"), "a");
|
|
4982
|
+
spawn(scoped ? "systemd-run" : plan.node, scoped ? [
|
|
4983
|
+
"--user",
|
|
4984
|
+
"--scope",
|
|
4985
|
+
"--collect",
|
|
4986
|
+
"--quiet",
|
|
4987
|
+
plan.node,
|
|
4988
|
+
...args
|
|
4989
|
+
] : args, {
|
|
4990
|
+
detached: true,
|
|
4991
|
+
stdio: [
|
|
4992
|
+
"ignore",
|
|
4993
|
+
logFile,
|
|
4994
|
+
logFile
|
|
4995
|
+
],
|
|
4996
|
+
windowsHide: true
|
|
4997
|
+
}).unref();
|
|
4998
|
+
}
|
|
4999
|
+
function readPlan(file) {
|
|
5000
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
5001
|
+
}
|
|
5002
|
+
/** Restart the daemon on `command.cli`: through the login service if there is one. */
|
|
5003
|
+
async function restartDaemon(command, dataDir) {
|
|
5004
|
+
if (isServiceInstalled(command.port)) {
|
|
5005
|
+
await installService(command, dataDir);
|
|
5006
|
+
return;
|
|
5007
|
+
}
|
|
5008
|
+
await stopDaemon(command.port);
|
|
5009
|
+
spawnDaemon(command, dataDir);
|
|
5010
|
+
}
|
|
5011
|
+
/**
|
|
5012
|
+
* The helper's job. Returns whether the daemon now runs `plan.version`;
|
|
5013
|
+
* when it doesn't, the old version runs again and the reason is in
|
|
5014
|
+
* `failureFile`.
|
|
5015
|
+
*/
|
|
5016
|
+
async function finishUpdate(plan, options = {}) {
|
|
5017
|
+
const { dataDir, port } = plan;
|
|
5018
|
+
const restart = options.restart ?? restartDaemon;
|
|
5019
|
+
const attempts = options.attempts ?? 300;
|
|
5020
|
+
const current = runtimeDir(dataDir, port);
|
|
5021
|
+
const previous = previousDir(dataDir, port);
|
|
5022
|
+
const command = (cli) => ({
|
|
5023
|
+
node: plan.node,
|
|
5024
|
+
cli,
|
|
5025
|
+
port,
|
|
5026
|
+
args: plan.flags
|
|
5027
|
+
});
|
|
5028
|
+
rmSync(planFile(dataDir, port), { force: true });
|
|
5029
|
+
rmSync(failureFile(dataDir, port), { force: true });
|
|
5030
|
+
rmSync(previous, {
|
|
5031
|
+
recursive: true,
|
|
5032
|
+
force: true
|
|
5033
|
+
});
|
|
5034
|
+
const hadRuntime = existsSync(current);
|
|
5035
|
+
try {
|
|
5036
|
+
if (hadRuntime) renameSync(current, previous);
|
|
5037
|
+
renameSync(stagingDir(dataDir, port), current);
|
|
5038
|
+
await restart(command(runtimeCli(dataDir, port)), dataDir);
|
|
5039
|
+
await waitForDaemon(port, dataDir, plan.version, attempts);
|
|
5040
|
+
rmSync(previous, {
|
|
5041
|
+
recursive: true,
|
|
5042
|
+
force: true
|
|
5043
|
+
});
|
|
5044
|
+
return true;
|
|
5045
|
+
} catch (error) {
|
|
5046
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
5047
|
+
writeFileSync(failureFile(dataDir, port), JSON.stringify({
|
|
5048
|
+
version: plan.version,
|
|
5049
|
+
error: message
|
|
5050
|
+
}));
|
|
5051
|
+
if (existsSync(previous)) {
|
|
5052
|
+
rmSync(current, {
|
|
5053
|
+
recursive: true,
|
|
5054
|
+
force: true
|
|
5055
|
+
});
|
|
5056
|
+
renameSync(previous, current);
|
|
5057
|
+
} else if (!hadRuntime) rmSync(current, {
|
|
5058
|
+
recursive: true,
|
|
5059
|
+
force: true
|
|
5060
|
+
});
|
|
5061
|
+
await restart(command(plan.previousCli), dataDir).catch(() => {});
|
|
5062
|
+
await waitForDaemon(port, dataDir, void 0, attempts).catch(() => {});
|
|
5063
|
+
return false;
|
|
5064
|
+
}
|
|
5065
|
+
}
|
|
5066
|
+
/** The rolled-back update's version and error, read once by the daemon that runs again. */
|
|
5067
|
+
function takeUpdateFailure(dataDir, port) {
|
|
5068
|
+
const file = failureFile(dataDir, port);
|
|
5069
|
+
try {
|
|
5070
|
+
const failure = JSON.parse(readFileSync(file, "utf8"));
|
|
5071
|
+
rmSync(file, { force: true });
|
|
5072
|
+
return failure;
|
|
5073
|
+
} catch {
|
|
5074
|
+
return;
|
|
5075
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
//#endregion
|
|
5078
|
+
//#region src/daemon/updates.ts
|
|
5079
|
+
const DAY_MS = 864e5;
|
|
5080
|
+
const HOUR_MS = 36e5;
|
|
5081
|
+
/**
|
|
5082
|
+
* Looks for new Tencil versions (on start, then about daily) and runs an
|
|
5083
|
+
* update started from the overlay: install it, wait until no thread is
|
|
5084
|
+
* running, then hand over to the helper that restarts the daemon on it.
|
|
5085
|
+
*
|
|
5086
|
+
* It waits rather than carrying threads across: Claude Code runs inside
|
|
5087
|
+
* the daemon, so a restart would end its running turns.
|
|
5088
|
+
*/
|
|
5089
|
+
var Updater = class {
|
|
5090
|
+
#options;
|
|
5091
|
+
#status = { state: "idle" };
|
|
5092
|
+
#timer;
|
|
5093
|
+
#restartTimer;
|
|
5094
|
+
#disposed = false;
|
|
5095
|
+
constructor(options) {
|
|
5096
|
+
this.#options = options;
|
|
5097
|
+
const failure = takeUpdateFailure(options.dataDir, options.port);
|
|
5098
|
+
if (failure) this.#status = {
|
|
5099
|
+
state: "failed",
|
|
5100
|
+
error: `Tencil ${failure.version} didn't start (${failure.error})`
|
|
5101
|
+
};
|
|
5102
|
+
}
|
|
5103
|
+
status() {
|
|
5104
|
+
return this.#status;
|
|
5105
|
+
}
|
|
5106
|
+
/** Check now and then on a timer. Never waits for the registry. */
|
|
5107
|
+
start() {
|
|
5108
|
+
const { check = !updateChecksDisabled() } = this.#options;
|
|
5109
|
+
if (check) this.check();
|
|
5110
|
+
}
|
|
5111
|
+
async check() {
|
|
5112
|
+
clearTimeout(this.#timer);
|
|
5113
|
+
const latest = await latestVersion({
|
|
5114
|
+
registry: this.#options.registry,
|
|
5115
|
+
timeoutMs: 5e3
|
|
5116
|
+
});
|
|
5117
|
+
if (this.#disposed) return;
|
|
5118
|
+
this.#timer = setTimeout(() => void this.check(), latest ? this.#options.intervalMs ?? DAY_MS : HOUR_MS);
|
|
5119
|
+
this.#timer.unref?.();
|
|
5120
|
+
if (!latest) return;
|
|
5121
|
+
const newer = compareVersions(latest, this.#options.version) > 0 ? latest : void 0;
|
|
5122
|
+
if (newer === this.#status.latest) return;
|
|
5123
|
+
this.#set({
|
|
5124
|
+
...this.#status,
|
|
5125
|
+
latest: newer
|
|
5126
|
+
});
|
|
5127
|
+
}
|
|
5128
|
+
/** Move to the latest version. Progress and failures arrive through `onChange`. */
|
|
5129
|
+
async update() {
|
|
5130
|
+
const { latest, state } = this.#status;
|
|
5131
|
+
if (state !== "idle" && state !== "failed") return;
|
|
5132
|
+
const { cli, dataDir, port, log } = this.#options;
|
|
5133
|
+
if (!latest) return this.#fail("Tencil is up to date");
|
|
5134
|
+
if (!cli) return this.#fail("This daemon wasn't started by the Tencil CLI");
|
|
5135
|
+
try {
|
|
5136
|
+
this.#set({
|
|
5137
|
+
latest,
|
|
5138
|
+
state: "installing"
|
|
5139
|
+
});
|
|
5140
|
+
log(`Installing Tencil ${latest}`);
|
|
5141
|
+
await stageUpdate(latest, {
|
|
5142
|
+
dataDir,
|
|
5143
|
+
port,
|
|
5144
|
+
install: this.#options.install
|
|
5145
|
+
});
|
|
5146
|
+
await this.#idle(latest);
|
|
5147
|
+
this.#set({
|
|
5148
|
+
latest,
|
|
5149
|
+
state: "restarting"
|
|
5150
|
+
});
|
|
5151
|
+
log(`Restarting on Tencil ${latest}`);
|
|
5152
|
+
(this.#options.handOff ?? ((plan) => handOffUpdate(plan, cli)))({
|
|
5153
|
+
version: latest,
|
|
5154
|
+
port,
|
|
5155
|
+
dataDir,
|
|
5156
|
+
node: this.#options.node,
|
|
5157
|
+
flags: this.#options.flags,
|
|
5158
|
+
previousCli: cli
|
|
5159
|
+
});
|
|
5160
|
+
this.#restartTimer = setTimeout(() => this.#fail(`Tencil ${latest} didn't take over. See daemon.log.`), this.#options.restartTimeoutMs ?? 12e4);
|
|
5161
|
+
this.#restartTimer.unref?.();
|
|
5162
|
+
} catch (error) {
|
|
5163
|
+
this.#fail(error instanceof Error ? error.message : String(error));
|
|
5164
|
+
}
|
|
5165
|
+
}
|
|
5166
|
+
dispose() {
|
|
5167
|
+
this.#disposed = true;
|
|
5168
|
+
clearTimeout(this.#timer);
|
|
5169
|
+
clearTimeout(this.#restartTimer);
|
|
5170
|
+
}
|
|
5171
|
+
async #idle(latest) {
|
|
5172
|
+
for (;;) {
|
|
5173
|
+
const running = await this.#options.running();
|
|
5174
|
+
if (!running) return;
|
|
5175
|
+
if (this.#status.state !== "waiting" || this.#status.running !== running) this.#set({
|
|
5176
|
+
latest,
|
|
5177
|
+
state: "waiting",
|
|
5178
|
+
running
|
|
5179
|
+
});
|
|
5180
|
+
await new Promise((resolve) => setTimeout(resolve, this.#options.idlePollMs ?? 1e3));
|
|
5181
|
+
if (this.#disposed) throw new Error("The daemon stopped");
|
|
5182
|
+
}
|
|
5183
|
+
}
|
|
5184
|
+
#fail(error) {
|
|
5185
|
+
this.#options.log(`Update failed: ${error}`);
|
|
5186
|
+
this.#set({
|
|
5187
|
+
latest: this.#status.latest,
|
|
5188
|
+
state: "failed",
|
|
5189
|
+
error
|
|
5190
|
+
});
|
|
5191
|
+
}
|
|
5192
|
+
#set(status) {
|
|
5193
|
+
this.#status = status;
|
|
5194
|
+
this.#options.onChange(status);
|
|
5195
|
+
}
|
|
5196
|
+
};
|
|
5197
|
+
//#endregion
|
|
3517
5198
|
//#region src/daemon/server.ts
|
|
3518
5199
|
const DEFAULT_PORT = 4747;
|
|
3519
5200
|
/** Screenshots ride along as data URLs. */
|
|
@@ -3532,13 +5213,19 @@ async function startDaemon(options = {}) {
|
|
|
3532
5213
|
const knownHosts = knownHostsFor(addresses, allowedOrigins);
|
|
3533
5214
|
const dataDir = options.dataDir ?? defaultDataDir();
|
|
3534
5215
|
const log = options.log ?? (() => {});
|
|
5216
|
+
const ensembleOptions = {
|
|
5217
|
+
baseUrl: options.ensemble?.url,
|
|
5218
|
+
credentials: options.ensemble?.credentials
|
|
5219
|
+
};
|
|
3535
5220
|
const resolver = new ProjectResolver({
|
|
3536
5221
|
dataDir,
|
|
3537
|
-
exec: options.exec
|
|
5222
|
+
exec: options.exec,
|
|
5223
|
+
ensembleForPort: (port) => ensembleProjectForPort(port, ensembleOptions)
|
|
3538
5224
|
});
|
|
3539
|
-
const resolveProject = options.resolveProject ?? ((pageUrl) => resolver.resolve(pageUrl));
|
|
5225
|
+
const resolveProject = options.resolveProject ?? ((pageUrl, root) => resolver.resolve(pageUrl, root));
|
|
3540
5226
|
const sessions = /* @__PURE__ */ new Map();
|
|
3541
5227
|
const overlayPath = resolveOverlayPath();
|
|
5228
|
+
let updater;
|
|
3542
5229
|
const claudeCodeDir = join(dataDir, "claude-code");
|
|
3543
5230
|
const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
|
|
3544
5231
|
const createProvider = options.createProvider ?? ((root, id) => {
|
|
@@ -3549,6 +5236,11 @@ async function startDaemon(options = {}) {
|
|
|
3549
5236
|
installDir: claudeCodeDir,
|
|
3550
5237
|
log: providerLog
|
|
3551
5238
|
});
|
|
5239
|
+
if (id === "ensemble") return new EnsembleProvider({
|
|
5240
|
+
projectRoot: root,
|
|
5241
|
+
...ensembleOptions,
|
|
5242
|
+
log: providerLog
|
|
5243
|
+
});
|
|
3552
5244
|
const { url, token, ...t3 } = options.t3 ?? {};
|
|
3553
5245
|
return new T3CodeProvider({
|
|
3554
5246
|
...t3,
|
|
@@ -3560,16 +5252,16 @@ async function startDaemon(options = {}) {
|
|
|
3560
5252
|
});
|
|
3561
5253
|
});
|
|
3562
5254
|
const session = (root) => {
|
|
3563
|
-
const key =
|
|
5255
|
+
const key = projectKey(root);
|
|
3564
5256
|
let pending = sessions.get(key);
|
|
3565
5257
|
if (!pending) {
|
|
3566
5258
|
pending = (async () => {
|
|
3567
5259
|
const providers = new ProjectProviders({
|
|
3568
5260
|
choices: PROVIDER_OPTIONS,
|
|
3569
|
-
fallback: options.provider ?? await machineProvider({
|
|
5261
|
+
fallback: options.provider ?? (ensembleThreadId(key) === void 0 ? await machineProvider({
|
|
3570
5262
|
dataDir,
|
|
3571
5263
|
t3Url
|
|
3572
|
-
}),
|
|
5264
|
+
}) : "ensemble"),
|
|
3573
5265
|
create: (id) => createProvider(key, id),
|
|
3574
5266
|
settings: new FileProjectSettings(projectSettingsPath(key, dataDir))
|
|
3575
5267
|
});
|
|
@@ -3583,6 +5275,7 @@ async function startDaemon(options = {}) {
|
|
|
3583
5275
|
root: key
|
|
3584
5276
|
},
|
|
3585
5277
|
version: VERSION,
|
|
5278
|
+
update: () => updater?.status() ?? { state: "idle" },
|
|
3586
5279
|
log: (message) => log(`[${basename(key)}] ${message}`)
|
|
3587
5280
|
});
|
|
3588
5281
|
log(`Serving ${key} with ${providers.default().label}`);
|
|
@@ -3590,6 +5283,7 @@ async function startDaemon(options = {}) {
|
|
|
3590
5283
|
root: key,
|
|
3591
5284
|
bridge,
|
|
3592
5285
|
providers,
|
|
5286
|
+
store,
|
|
3593
5287
|
clients: 0
|
|
3594
5288
|
};
|
|
3595
5289
|
})();
|
|
@@ -3597,21 +5291,29 @@ async function startDaemon(options = {}) {
|
|
|
3597
5291
|
}
|
|
3598
5292
|
return pending;
|
|
3599
5293
|
};
|
|
3600
|
-
/** Projects
|
|
5294
|
+
/** Projects any agent knows, offered when a page's project can't be worked out. */
|
|
3601
5295
|
const choices = async () => {
|
|
3602
|
-
const [t3, claude] = await Promise.all([
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
|
|
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
|
+
]);
|
|
3607
5305
|
const byRoot = /* @__PURE__ */ new Map();
|
|
3608
|
-
for (const project of [
|
|
5306
|
+
for (const project of [
|
|
5307
|
+
...t3,
|
|
5308
|
+
...claude,
|
|
5309
|
+
...ensemble
|
|
5310
|
+
]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
|
|
3609
5311
|
root: project.workspaceRoot,
|
|
3610
5312
|
title: project.title
|
|
3611
5313
|
});
|
|
3612
5314
|
return [...byRoot.values()];
|
|
3613
5315
|
};
|
|
3614
|
-
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.";
|
|
3615
5317
|
const settled = async () => (await Promise.allSettled(sessions.values())).filter((r) => r.status === "fulfilled").map((r) => r.value);
|
|
3616
5318
|
let statuses = [];
|
|
3617
5319
|
const refreshStatuses = async () => {
|
|
@@ -3692,7 +5394,8 @@ async function startDaemon(options = {}) {
|
|
|
3692
5394
|
const message = raw;
|
|
3693
5395
|
if (message.type === "hello") {
|
|
3694
5396
|
pageUrl = message.pageUrl ?? "";
|
|
3695
|
-
const
|
|
5397
|
+
const claimed = typeof message.root === "string" ? message.root : void 0;
|
|
5398
|
+
const root = await resolveProject(pageUrl, claimed).catch(() => void 0);
|
|
3696
5399
|
if (root) return attach(root, raw);
|
|
3697
5400
|
return client.send({
|
|
3698
5401
|
type: "project.unknown",
|
|
@@ -3701,6 +5404,11 @@ async function startDaemon(options = {}) {
|
|
|
3701
5404
|
emptyHint: noChoicesHint
|
|
3702
5405
|
});
|
|
3703
5406
|
}
|
|
5407
|
+
if (message.type === "update.start") {
|
|
5408
|
+
if (!updater) throw new Error("Tencil can't update itself yet");
|
|
5409
|
+
updater.update();
|
|
5410
|
+
return;
|
|
5411
|
+
}
|
|
3704
5412
|
if (message.type === "project.select" && message.root) {
|
|
3705
5413
|
await resolver.remember(pageUrl, message.root);
|
|
3706
5414
|
return attach(message.root, {
|
|
@@ -3755,6 +5463,25 @@ async function startDaemon(options = {}) {
|
|
|
3755
5463
|
for (const server of servers) server.close();
|
|
3756
5464
|
throw error;
|
|
3757
5465
|
}
|
|
5466
|
+
updater = new Updater({
|
|
5467
|
+
...options.updates,
|
|
5468
|
+
version: VERSION,
|
|
5469
|
+
dataDir,
|
|
5470
|
+
port: actualPort,
|
|
5471
|
+
node: process.execPath,
|
|
5472
|
+
cli: options.cli,
|
|
5473
|
+
flags: options.flags ?? [],
|
|
5474
|
+
running: async () => (await settled()).flatMap((s) => s.store.list()).filter((thread) => thread.status === "starting" || thread.status === "working").length,
|
|
5475
|
+
onChange: (update) => {
|
|
5476
|
+
const message = JSON.stringify({
|
|
5477
|
+
type: "update",
|
|
5478
|
+
update
|
|
5479
|
+
});
|
|
5480
|
+
for (const ws of wss.clients) if (ws.readyState === WebSocket$1.OPEN) ws.send(message);
|
|
5481
|
+
},
|
|
5482
|
+
log
|
|
5483
|
+
});
|
|
5484
|
+
updater.start();
|
|
3758
5485
|
const url = `http://${host === "127.0.0.1" || host === "0.0.0.0" ? "localhost" : host}:${actualPort}`;
|
|
3759
5486
|
log(`Tencil daemon listening on ${url}`);
|
|
3760
5487
|
for (const extra of addresses.slice(1)) log(`Also listening on http://${extra}:${actualPort}`);
|
|
@@ -3763,7 +5490,9 @@ async function startDaemon(options = {}) {
|
|
|
3763
5490
|
scriptUrl: `${url}/tencil.js`,
|
|
3764
5491
|
port: actualPort,
|
|
3765
5492
|
projects: () => statuses,
|
|
5493
|
+
checkForUpdates: () => updater?.check() ?? Promise.resolve(),
|
|
3766
5494
|
async close() {
|
|
5495
|
+
updater?.dispose();
|
|
3767
5496
|
for (const ws of wss.clients) ws.terminate();
|
|
3768
5497
|
for (const s of await settled()) {
|
|
3769
5498
|
await s.bridge.dispose();
|
|
@@ -3797,4 +5526,4 @@ function resolveOverlayPath() {
|
|
|
3797
5526
|
return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
|
|
3798
5527
|
}
|
|
3799
5528
|
//#endregion
|
|
3800
|
-
export {
|
|
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 };
|