tencil 0.8.0 → 0.10.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 +23 -5
- package/dist/cli.mjs +33 -5
- package/dist/{cloud-DPNrsIER.d.mts → cloud-DKtU6lcZ.d.mts} +1 -1
- package/dist/{index-C4SmNUQW.d.mts → index-BSKV-nDI.d.mts} +99 -1
- package/dist/index.d.mts +42 -11
- package/dist/index.mjs +1 -1
- package/dist/next.d.mts +1 -1
- package/dist/overlay.global.js +208 -62
- package/dist/react.d.mts +1 -1
- package/dist/{server-Cbvie3Om.mjs → server-C-Udis96.mjs} +1183 -79
- package/dist/vite.d.mts +1 -1
- package/package.json +6 -5
|
@@ -4,10 +4,11 @@ import { existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writ
|
|
|
4
4
|
import { access, chmod, mkdir, readFile, readlink, realpath, rename, writeFile } from "node:fs/promises";
|
|
5
5
|
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
|
-
import { createServer } from "node:http";
|
|
8
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
7
|
import { createHash, randomUUID } from "node:crypto";
|
|
10
8
|
import { homedir } from "node:os";
|
|
9
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
10
|
+
import { createServer } from "node:http";
|
|
11
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
12
|
import { WebSocket as WebSocket$1, WebSocketServer } from "ws";
|
|
12
13
|
//#region ../protocol/src/context.ts
|
|
13
14
|
/** A resolved source location for the element, usually from React's owner stack. */
|
|
@@ -111,6 +112,42 @@ const BuildInfo = z.object({
|
|
|
111
112
|
branch: z.string().min(1).max(255),
|
|
112
113
|
sha: z.string().min(7).max(64)
|
|
113
114
|
});
|
|
115
|
+
/** A key combination, matched by key position (`code`) so it works on any layout. */
|
|
116
|
+
const Shortcut = z.object({
|
|
117
|
+
code: z.string().min(1).max(32),
|
|
118
|
+
/** What the layout prints for it, for labels. */
|
|
119
|
+
key: z.string().min(1).max(32),
|
|
120
|
+
alt: z.boolean(),
|
|
121
|
+
ctrl: z.boolean(),
|
|
122
|
+
meta: z.boolean(),
|
|
123
|
+
shift: z.boolean()
|
|
124
|
+
});
|
|
125
|
+
const Shortcuts = z.object({
|
|
126
|
+
comment: Shortcut.nullable(),
|
|
127
|
+
ruler: Shortcut.nullable(),
|
|
128
|
+
hidePins: Shortcut.nullable(),
|
|
129
|
+
/** Never cleared: it's the only way back to a hidden dock. */
|
|
130
|
+
hideDock: Shortcut,
|
|
131
|
+
/** Held, not pressed. */
|
|
132
|
+
measure: z.enum([
|
|
133
|
+
"Alt",
|
|
134
|
+
"Control",
|
|
135
|
+
"Meta",
|
|
136
|
+
"Shift"
|
|
137
|
+
]).nullable()
|
|
138
|
+
});
|
|
139
|
+
/**
|
|
140
|
+
* The person's own overlay settings, the same in every project on the machine.
|
|
141
|
+
* Saved by the local daemon; unset ones fall back to the overlay's defaults.
|
|
142
|
+
*/
|
|
143
|
+
const Preferences = z.object({
|
|
144
|
+
theme: z.enum([
|
|
145
|
+
"dark",
|
|
146
|
+
"light",
|
|
147
|
+
"system"
|
|
148
|
+
]).optional(),
|
|
149
|
+
shortcuts: Shortcuts.optional()
|
|
150
|
+
});
|
|
114
151
|
const ClientMessage = z.discriminatedUnion("type", [
|
|
115
152
|
z.object({
|
|
116
153
|
type: z.literal("hello"),
|
|
@@ -157,6 +194,7 @@ const ClientMessage = z.discriminatedUnion("type", [
|
|
|
157
194
|
}),
|
|
158
195
|
z.object({ type: z.literal("provider.threads") }),
|
|
159
196
|
z.object({ type: z.literal("provider.models") }),
|
|
197
|
+
z.object({ type: z.literal("project.choices") }),
|
|
160
198
|
z.object({
|
|
161
199
|
type: z.literal("project.select"),
|
|
162
200
|
root: z.string().min(1)
|
|
@@ -196,7 +234,11 @@ const ClientMessage = z.discriminatedUnion("type", [
|
|
|
196
234
|
type: z.literal("model.select"),
|
|
197
235
|
model: z.string().min(1).nullable()
|
|
198
236
|
}),
|
|
199
|
-
z.object({ type: z.literal("update.start") })
|
|
237
|
+
z.object({ type: z.literal("update.start") }),
|
|
238
|
+
z.object({
|
|
239
|
+
type: z.literal("preferences.update"),
|
|
240
|
+
preferences: Preferences
|
|
241
|
+
})
|
|
200
242
|
]);
|
|
201
243
|
z.object({
|
|
202
244
|
id: z.string(),
|
|
@@ -229,6 +271,27 @@ z.object({
|
|
|
229
271
|
/** The toolbar offers the ruler: spacing while picking, distances with Alt. */
|
|
230
272
|
ruler: z.boolean()
|
|
231
273
|
});
|
|
274
|
+
/**
|
|
275
|
+
* How the daemon matched the page to its project: an Ensemble thread's dev
|
|
276
|
+
* server, the git root the Vite or Next plugin passed, the dev server listening
|
|
277
|
+
* on the page's port, the Docker container publishing it, or a pick in the overlay.
|
|
278
|
+
*/
|
|
279
|
+
const DetectedVia = z.enum([
|
|
280
|
+
"ensemble",
|
|
281
|
+
"plugin",
|
|
282
|
+
"port",
|
|
283
|
+
"docker"
|
|
284
|
+
]);
|
|
285
|
+
z.object({
|
|
286
|
+
via: z.enum([...DetectedVia.options, "picked"]),
|
|
287
|
+
port: z.number().int().optional(),
|
|
288
|
+
/** Picked over a project Tencil did detect: that one, to go back to. */
|
|
289
|
+
detected: z.object({
|
|
290
|
+
root: z.string(),
|
|
291
|
+
via: DetectedVia,
|
|
292
|
+
port: z.number().int().optional()
|
|
293
|
+
}).optional()
|
|
294
|
+
});
|
|
232
295
|
//#endregion
|
|
233
296
|
//#region ../protocol/src/thread.ts
|
|
234
297
|
/**
|
|
@@ -341,7 +404,9 @@ const Thread = z.object({
|
|
|
341
404
|
id: z.string(),
|
|
342
405
|
threadId: z.string().optional(),
|
|
343
406
|
/** Deep link into the provider UI, when it has one. */
|
|
344
|
-
url: z.string().optional()
|
|
407
|
+
url: z.string().optional(),
|
|
408
|
+
/** Started for these pins: archived once they're all resolved (`Provider.archive`). */
|
|
409
|
+
archivable: z.boolean().optional()
|
|
345
410
|
}),
|
|
346
411
|
/** Tencil Cloud only: the run's commit, pull request and preview. */
|
|
347
412
|
delivery: Delivery.optional(),
|
|
@@ -538,7 +603,7 @@ var Bridge = class {
|
|
|
538
603
|
type: "settings",
|
|
539
604
|
settings: this.#settings()
|
|
540
605
|
}));
|
|
541
|
-
for (const thread of options.store.list()) if (thread.provider.threadId && options.providers.has(thread.provider.id)) this.#watch(thread.provider.id, thread.provider.threadId);
|
|
606
|
+
for (const thread of options.store.list()) if (thread.provider.threadId && options.providers.has(thread.provider.id) && !this.#archived(thread.provider)) this.#watch(thread.provider.id, thread.provider.threadId);
|
|
542
607
|
}
|
|
543
608
|
connect(client) {
|
|
544
609
|
this.#clients.add(client);
|
|
@@ -633,10 +698,7 @@ var Bridge = class {
|
|
|
633
698
|
return;
|
|
634
699
|
}
|
|
635
700
|
case "thread.resolve":
|
|
636
|
-
this.#
|
|
637
|
-
...thread,
|
|
638
|
-
resolved: message.resolved
|
|
639
|
-
}));
|
|
701
|
+
await this.#resolve(message.threadId, message.resolved);
|
|
640
702
|
return;
|
|
641
703
|
case "thread.move":
|
|
642
704
|
this.#update(message.threadId, (thread) => ({
|
|
@@ -645,16 +707,20 @@ var Bridge = class {
|
|
|
645
707
|
}));
|
|
646
708
|
return;
|
|
647
709
|
case "thread.delete": {
|
|
648
|
-
const
|
|
710
|
+
const thread = this.#options.store.get(message.threadId);
|
|
649
711
|
this.#draftAttachments.delete(message.threadId);
|
|
650
712
|
if (this.#options.store.delete(message.threadId)) this.#broadcast({
|
|
651
713
|
type: "thread.removed",
|
|
652
714
|
threadId: message.threadId
|
|
653
715
|
});
|
|
654
|
-
if (
|
|
716
|
+
if (!thread?.provider.threadId) return;
|
|
717
|
+
if (!thread.resolved && this.#options.providers.has(thread.provider.id) && this.#archived(thread.provider)) await this.#archive(thread);
|
|
718
|
+
this.#release(thread.provider.id, thread.provider.threadId);
|
|
655
719
|
return;
|
|
656
720
|
}
|
|
657
721
|
case "update.start": throw new Error("Tencil can't update itself here");
|
|
722
|
+
case "preferences.update": throw new Error("Preferences aren't saved here");
|
|
723
|
+
case "project.choices": throw new Error("Projects can't be switched here");
|
|
658
724
|
}
|
|
659
725
|
} catch (error) {
|
|
660
726
|
const threadId = "threadId" in message ? message.threadId : void 0;
|
|
@@ -711,7 +777,8 @@ var Bridge = class {
|
|
|
711
777
|
provider: {
|
|
712
778
|
id: provider.id,
|
|
713
779
|
threadId: created.providerThreadId,
|
|
714
|
-
url: created.url
|
|
780
|
+
url: created.url,
|
|
781
|
+
archivable: created.archivable
|
|
715
782
|
}
|
|
716
783
|
}));
|
|
717
784
|
this.#watch(provider.id, created.providerThreadId);
|
|
@@ -798,7 +865,8 @@ var Bridge = class {
|
|
|
798
865
|
provider: {
|
|
799
866
|
id: provider.id,
|
|
800
867
|
threadId: created.providerThreadId,
|
|
801
|
-
url: created.url
|
|
868
|
+
url: created.url,
|
|
869
|
+
archivable: created.archivable
|
|
802
870
|
}
|
|
803
871
|
}));
|
|
804
872
|
}
|
|
@@ -834,7 +902,8 @@ var Bridge = class {
|
|
|
834
902
|
provider: {
|
|
835
903
|
id: provider.id,
|
|
836
904
|
threadId: providerThreadId,
|
|
837
|
-
url: provider.threadUrl(providerThreadId)
|
|
905
|
+
url: provider.threadUrl(providerThreadId),
|
|
906
|
+
archivable: sibling?.provider.archivable
|
|
838
907
|
},
|
|
839
908
|
createdAt: now,
|
|
840
909
|
updatedAt: now
|
|
@@ -883,7 +952,8 @@ var Bridge = class {
|
|
|
883
952
|
provider: {
|
|
884
953
|
id: provider.id,
|
|
885
954
|
threadId: message.providerThreadId,
|
|
886
|
-
url: provider.threadUrl(message.providerThreadId)
|
|
955
|
+
url: provider.threadUrl(message.providerThreadId),
|
|
956
|
+
archivable: sibling?.provider.archivable
|
|
887
957
|
},
|
|
888
958
|
createdAt: now,
|
|
889
959
|
updatedAt: now
|
|
@@ -895,9 +965,9 @@ var Bridge = class {
|
|
|
895
965
|
async #reply(message) {
|
|
896
966
|
const thread = this.#require(message.threadId);
|
|
897
967
|
if (!thread.provider.threadId) throw new Error("This pin has no agent thread yet");
|
|
968
|
+
await this.#resolve(thread.id, false);
|
|
898
969
|
this.#update(thread.id, (current) => ({
|
|
899
970
|
...current,
|
|
900
|
-
resolved: false,
|
|
901
971
|
status: "working",
|
|
902
972
|
statusDetail: void 0,
|
|
903
973
|
steps: void 0,
|
|
@@ -910,6 +980,43 @@ var Bridge = class {
|
|
|
910
980
|
});
|
|
911
981
|
}
|
|
912
982
|
/**
|
|
983
|
+
* A thread the provider started for its pins is archived once every pin on it is
|
|
984
|
+
* resolved, and reopened when one is reopened. It isn't watched while archived.
|
|
985
|
+
*/
|
|
986
|
+
async #resolve(threadId, resolved) {
|
|
987
|
+
const thread = this.#require(threadId);
|
|
988
|
+
if (thread.resolved === resolved) return;
|
|
989
|
+
const { id: providerId, threadId: providerThreadId, archivable } = thread.provider;
|
|
990
|
+
const others = providerThreadId ? this.#pinsFor(providerId, providerThreadId).filter((pin) => pin.id !== threadId) : [];
|
|
991
|
+
if (archivable && providerThreadId && others.every((pin) => pin.resolved)) {
|
|
992
|
+
if (resolved) await this.#archive(thread);
|
|
993
|
+
else {
|
|
994
|
+
await this.#providerOf(thread).reopen?.(providerThreadId);
|
|
995
|
+
this.#watch(providerId, providerThreadId, true);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
this.#update(threadId, (current) => ({
|
|
999
|
+
...current,
|
|
1000
|
+
resolved
|
|
1001
|
+
}));
|
|
1002
|
+
}
|
|
1003
|
+
/** Archive the pin's provider thread, which its other pins, if any, are done with. */
|
|
1004
|
+
async #archive(thread) {
|
|
1005
|
+
const { id: providerId, threadId: providerThreadId } = thread.provider;
|
|
1006
|
+
if (!providerThreadId) return;
|
|
1007
|
+
this.#unwatch(providerId, providerThreadId);
|
|
1008
|
+
try {
|
|
1009
|
+
await this.#providerOf(thread).archive?.(providerThreadId);
|
|
1010
|
+
} catch (error) {
|
|
1011
|
+
if (this.#pinsFor(providerId, providerThreadId).length > 0) this.#watch(providerId, providerThreadId);
|
|
1012
|
+
throw error;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
/** Whether the provider thread is archived: started for its pins, which are all resolved. */
|
|
1016
|
+
#archived(provider) {
|
|
1017
|
+
return provider.archivable === true && provider.threadId !== void 0 && this.#pinsFor(provider.id, provider.threadId).every((pin) => pin.resolved);
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
913
1020
|
* Subscribe once per provider thread and fan updates out to every bound pin.
|
|
914
1021
|
* `replay` re-subscribes an existing watch so a newly bound pin receives the
|
|
915
1022
|
* provider's snapshot too.
|
|
@@ -943,7 +1050,9 @@ var Bridge = class {
|
|
|
943
1050
|
this.#watches.set(key, unwatch);
|
|
944
1051
|
}
|
|
945
1052
|
#release(providerId, providerThreadId) {
|
|
946
|
-
if (this.#pinsFor(providerId, providerThreadId).length
|
|
1053
|
+
if (this.#pinsFor(providerId, providerThreadId).length === 0) this.#unwatch(providerId, providerThreadId);
|
|
1054
|
+
}
|
|
1055
|
+
#unwatch(providerId, providerThreadId) {
|
|
947
1056
|
const key = watchKey(providerId, providerThreadId);
|
|
948
1057
|
this.#watches.get(key)?.();
|
|
949
1058
|
this.#watches.delete(key);
|
|
@@ -1210,6 +1319,772 @@ function settleInterrupted(thread) {
|
|
|
1210
1319
|
statusDetail: "Bridge stopped before the thread was created"
|
|
1211
1320
|
};
|
|
1212
1321
|
}
|
|
1322
|
+
/** Where Ensemble's public API listens; `TENCIL_ENSEMBLE_URL` points elsewhere. */
|
|
1323
|
+
function ensembleUrl() {
|
|
1324
|
+
return process.env.TENCIL_ENSEMBLE_URL ?? "http://127.0.0.1:7434";
|
|
1325
|
+
}
|
|
1326
|
+
var EnsembleHttpError = class extends Error {
|
|
1327
|
+
status;
|
|
1328
|
+
constructor(status, reason) {
|
|
1329
|
+
super(`Ensemble returned ${status}: ${reason}`);
|
|
1330
|
+
this.status = status;
|
|
1331
|
+
this.name = "EnsembleHttpError";
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
/** The token is missing, or the user removed Tencil in Ensemble › Settings › Ensemble API. */
|
|
1335
|
+
var EnsembleUnauthorizedError = class extends EnsembleHttpError {
|
|
1336
|
+
constructor(reason) {
|
|
1337
|
+
super(401, reason);
|
|
1338
|
+
this.name = "EnsembleUnauthorizedError";
|
|
1339
|
+
}
|
|
1340
|
+
};
|
|
1341
|
+
/** Ensemble's public local API. Every write carries an idempotency key. */
|
|
1342
|
+
var EnsembleClient = class {
|
|
1343
|
+
baseUrl;
|
|
1344
|
+
#token;
|
|
1345
|
+
#timeoutMs;
|
|
1346
|
+
constructor(options = {}) {
|
|
1347
|
+
this.baseUrl = new URL(options.baseUrl ?? ensembleUrl()).origin;
|
|
1348
|
+
this.#token = options.token;
|
|
1349
|
+
this.#timeoutMs = options.timeoutMs ?? 1e4;
|
|
1350
|
+
}
|
|
1351
|
+
/** Whether the Ensemble app is running; this needs no token. */
|
|
1352
|
+
async isRunning() {
|
|
1353
|
+
try {
|
|
1354
|
+
const about = await this.#request("GET", "", {
|
|
1355
|
+
auth: false,
|
|
1356
|
+
timeoutMs: 1500
|
|
1357
|
+
});
|
|
1358
|
+
return about.name === "ensemble" && about.api === 1;
|
|
1359
|
+
} catch {
|
|
1360
|
+
return false;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
/** Ask the user to allow Tencil. Ensemble keeps the request open while it asks, up to 2 minutes. */
|
|
1364
|
+
async connect() {
|
|
1365
|
+
const { token } = await this.#request("POST", "connect", {
|
|
1366
|
+
body: {
|
|
1367
|
+
name: "Tencil",
|
|
1368
|
+
access: "work"
|
|
1369
|
+
},
|
|
1370
|
+
auth: false,
|
|
1371
|
+
timeoutMs: 125e3
|
|
1372
|
+
});
|
|
1373
|
+
return token;
|
|
1374
|
+
}
|
|
1375
|
+
projects() {
|
|
1376
|
+
return this.#request("GET", "projects");
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Open threads; with `port`, only the one whose app listens on that port of this Mac,
|
|
1380
|
+
* with `project`, only that project's.
|
|
1381
|
+
*/
|
|
1382
|
+
threads(filter = {}) {
|
|
1383
|
+
const query = new URLSearchParams();
|
|
1384
|
+
if (filter.port !== void 0) query.set("port", String(filter.port));
|
|
1385
|
+
if (filter.project !== void 0) query.set("project", filter.project);
|
|
1386
|
+
return this.#request("GET", query.size ? `threads?${query}` : "threads");
|
|
1387
|
+
}
|
|
1388
|
+
/** A new thread in `projectId`, on its own branch; its first chat runs `prompt`. */
|
|
1389
|
+
createThread(thread) {
|
|
1390
|
+
return this.#request("POST", "threads", { body: thread });
|
|
1391
|
+
}
|
|
1392
|
+
thread(threadId) {
|
|
1393
|
+
return this.#request("GET", threadPath(threadId));
|
|
1394
|
+
}
|
|
1395
|
+
/** Saves the thread's work and conversation, and frees its machine. */
|
|
1396
|
+
archiveThread(threadId) {
|
|
1397
|
+
return this.#request("POST", `${threadPath(threadId)}/archive`, { body: {} });
|
|
1398
|
+
}
|
|
1399
|
+
/** Brings an archived thread back on a new machine with its saved work. */
|
|
1400
|
+
reopenThread(threadId) {
|
|
1401
|
+
return this.#request("POST", `${threadPath(threadId)}/reopen`, { body: {} });
|
|
1402
|
+
}
|
|
1403
|
+
createChat(threadId, chat) {
|
|
1404
|
+
return this.#request("POST", `${threadPath(threadId)}/chats`, { body: chat });
|
|
1405
|
+
}
|
|
1406
|
+
/** Queues behind a running turn. */
|
|
1407
|
+
sendMessage(threadId, chatId, message) {
|
|
1408
|
+
return this.#request("POST", `${chatPath(threadId, chatId)}/messages`, { body: message });
|
|
1409
|
+
}
|
|
1410
|
+
stop(threadId, chatId) {
|
|
1411
|
+
return this.#request("POST", `${chatPath(threadId, chatId)}/stop`, { body: {} });
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* A thread's events, every chat included, until the feed fails. Without `after` it
|
|
1415
|
+
* starts with the whole state. Ensemble pings every 15 s, so a feed silent for
|
|
1416
|
+
* `silenceMs` counts as dropped.
|
|
1417
|
+
*/
|
|
1418
|
+
async *feed(threadId, options) {
|
|
1419
|
+
const silenceMs = options.silenceMs ?? 45e3;
|
|
1420
|
+
const silent = new AbortController();
|
|
1421
|
+
let timer = setTimeout(() => silent.abort(), silenceMs);
|
|
1422
|
+
const heard = () => {
|
|
1423
|
+
clearTimeout(timer);
|
|
1424
|
+
timer = setTimeout(() => silent.abort(), silenceMs);
|
|
1425
|
+
};
|
|
1426
|
+
try {
|
|
1427
|
+
const response = await this.#fetch("GET", `feed?thread=${encodeURIComponent(threadId)}`, {
|
|
1428
|
+
headers: {
|
|
1429
|
+
Accept: "text/event-stream",
|
|
1430
|
+
...options.after ? { "Last-Event-ID": options.after } : {}
|
|
1431
|
+
},
|
|
1432
|
+
signal: AbortSignal.any([options.signal, silent.signal])
|
|
1433
|
+
});
|
|
1434
|
+
if (!response.body) throw new Error("Ensemble sent an empty feed");
|
|
1435
|
+
for await (const message of serverSentEvents(response.body, heard)) {
|
|
1436
|
+
const data = JSON.parse(message.data);
|
|
1437
|
+
const type = data.type ?? message.event;
|
|
1438
|
+
if (type === "error") throw new Error(`Ensemble ended the feed: ${data.error}`);
|
|
1439
|
+
yield {
|
|
1440
|
+
id: message.id,
|
|
1441
|
+
event: {
|
|
1442
|
+
...data,
|
|
1443
|
+
type
|
|
1444
|
+
}
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
throw new Error("Ensemble closed the feed");
|
|
1448
|
+
} finally {
|
|
1449
|
+
clearTimeout(timer);
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
async #request(method, path, options = {}) {
|
|
1453
|
+
const response = await this.#fetch(method, path, {
|
|
1454
|
+
auth: options.auth,
|
|
1455
|
+
headers: options.body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
1456
|
+
body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
|
|
1457
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? this.#timeoutMs)
|
|
1458
|
+
});
|
|
1459
|
+
if (response.status === 204) return void 0;
|
|
1460
|
+
return await response.json();
|
|
1461
|
+
}
|
|
1462
|
+
async #fetch(method, path, init) {
|
|
1463
|
+
const response = await fetch(`${this.baseUrl}/v1${path ? `/${path}` : ""}`, {
|
|
1464
|
+
method,
|
|
1465
|
+
headers: {
|
|
1466
|
+
...init.headers,
|
|
1467
|
+
...init.auth === false ? {} : { Authorization: `Bearer ${this.#token ?? ""}` },
|
|
1468
|
+
...method === "POST" ? { "Idempotency-Key": randomUUID() } : {}
|
|
1469
|
+
},
|
|
1470
|
+
body: init.body,
|
|
1471
|
+
signal: init.signal
|
|
1472
|
+
});
|
|
1473
|
+
if (response.ok) return response;
|
|
1474
|
+
const { error } = await response.json().catch(() => ({}));
|
|
1475
|
+
const reason = error ?? response.statusText;
|
|
1476
|
+
throw response.status === 401 ? new EnsembleUnauthorizedError(reason) : new EnsembleHttpError(response.status, reason);
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
function errorMessage$2(error) {
|
|
1480
|
+
return error instanceof Error ? error.message : String(error);
|
|
1481
|
+
}
|
|
1482
|
+
function threadPath(threadId) {
|
|
1483
|
+
return `threads/${encodeURIComponent(threadId)}`;
|
|
1484
|
+
}
|
|
1485
|
+
function chatPath(threadId, chatId) {
|
|
1486
|
+
return `${threadPath(threadId)}/chats/${encodeURIComponent(chatId)}`;
|
|
1487
|
+
}
|
|
1488
|
+
/** Events from a text/event-stream body. `heard` runs on every chunk, pings included. */
|
|
1489
|
+
async function* serverSentEvents(body, heard) {
|
|
1490
|
+
let partial = "";
|
|
1491
|
+
let fields = { data: [] };
|
|
1492
|
+
for await (const chunk of body.pipeThrough(new TextDecoderStream())) {
|
|
1493
|
+
heard();
|
|
1494
|
+
const lines = (partial + chunk).split(/\r?\n/);
|
|
1495
|
+
partial = lines.pop() ?? "";
|
|
1496
|
+
for (const line of lines) if (line === "") {
|
|
1497
|
+
if (fields.data.length) yield {
|
|
1498
|
+
event: fields.event ?? "message",
|
|
1499
|
+
id: fields.id,
|
|
1500
|
+
data: fields.data.join("\n")
|
|
1501
|
+
};
|
|
1502
|
+
fields = { data: [] };
|
|
1503
|
+
} else if (!line.startsWith(":")) {
|
|
1504
|
+
const [field, value] = splitField(line);
|
|
1505
|
+
if (field === "event") fields.event = value;
|
|
1506
|
+
else if (field === "id") fields.id = value;
|
|
1507
|
+
else if (field === "data") fields.data.push(value);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
/** `field: value`, without the one optional space after the colon. */
|
|
1512
|
+
function splitField(line) {
|
|
1513
|
+
const colon = line.indexOf(":");
|
|
1514
|
+
if (colon < 0) return [line, ""];
|
|
1515
|
+
return [line.slice(0, colon), line.slice(colon + 1).replace(/^ /, "")];
|
|
1516
|
+
}
|
|
1517
|
+
//#endregion
|
|
1518
|
+
//#region ../provider-ensemble/src/auth.ts
|
|
1519
|
+
/** The tokens Ensemble gave Tencil, per Ensemble URL, readable only by this user. */
|
|
1520
|
+
var EnsembleCredentialStore = class {
|
|
1521
|
+
path;
|
|
1522
|
+
constructor(path = join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "tencil", "ensemble-credentials.json")) {
|
|
1523
|
+
this.path = path;
|
|
1524
|
+
}
|
|
1525
|
+
async get(baseUrl) {
|
|
1526
|
+
return (await this.#read())[new URL(baseUrl).origin];
|
|
1527
|
+
}
|
|
1528
|
+
async set(baseUrl, token) {
|
|
1529
|
+
const tokens = await this.#read();
|
|
1530
|
+
tokens[new URL(baseUrl).origin] = token;
|
|
1531
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
1532
|
+
await writeFile(this.path, `${JSON.stringify(tokens, null, 2)}\n`, { mode: 384 });
|
|
1533
|
+
await chmod(this.path, 384);
|
|
1534
|
+
}
|
|
1535
|
+
async #read() {
|
|
1536
|
+
try {
|
|
1537
|
+
return JSON.parse(await readFile(this.path, "utf8"));
|
|
1538
|
+
} catch {
|
|
1539
|
+
return {};
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
//#endregion
|
|
1544
|
+
//#region ../provider-ensemble/src/folders.ts
|
|
1545
|
+
const run$2 = promisify(execFile);
|
|
1546
|
+
/**
|
|
1547
|
+
* The Ensemble target for a page whose dev server runs in `folder`:
|
|
1548
|
+
* - inside an Ensemble project's folder, it's the user's own checkout: each pin starts a thread.
|
|
1549
|
+
* - on the branch of one open thread, it's that thread's workspace: pins go to the thread.
|
|
1550
|
+
* - a worktree of a project's repository counts as that project.
|
|
1551
|
+
*/
|
|
1552
|
+
async function targetForFolder(client, folder) {
|
|
1553
|
+
const dir = await realpath(folder).catch(() => folder);
|
|
1554
|
+
const [projects, git] = await Promise.all([client.projects(), gitInfo(dir)]);
|
|
1555
|
+
const local = (await Promise.all(projects.map(async (project) => project.source.kind === "local" ? {
|
|
1556
|
+
project,
|
|
1557
|
+
path: await realpath(project.source.path).catch(() => "")
|
|
1558
|
+
} : void 0))).filter((entry) => entry?.path);
|
|
1559
|
+
const own = deepest(local, dir);
|
|
1560
|
+
if (own) return {
|
|
1561
|
+
kind: "project",
|
|
1562
|
+
project: own
|
|
1563
|
+
};
|
|
1564
|
+
if (git?.branch) {
|
|
1565
|
+
const threads = (await client.threads()).filter((thread) => thread.branch === git.branch);
|
|
1566
|
+
if (threads.length === 1 && threads[0]) return {
|
|
1567
|
+
kind: "thread",
|
|
1568
|
+
threadId: threads[0].id
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
if (git?.main) {
|
|
1572
|
+
const project = deepest(local, join(git.main, relative(git.top, dir)));
|
|
1573
|
+
if (project) return {
|
|
1574
|
+
kind: "project",
|
|
1575
|
+
project
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
return {
|
|
1579
|
+
kind: "missing",
|
|
1580
|
+
repository: git?.main ?? git?.top ?? dir
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
/** The project whose folder holds `dir` most closely. */
|
|
1584
|
+
function deepest(folders, dir) {
|
|
1585
|
+
let best;
|
|
1586
|
+
for (const { project, path } of folders) {
|
|
1587
|
+
if (dir !== path && !dir.startsWith(path.endsWith(sep) ? path : `${path}${sep}`)) continue;
|
|
1588
|
+
const depth = path.split(sep).length;
|
|
1589
|
+
if (!best || depth > best.depth) best = {
|
|
1590
|
+
project,
|
|
1591
|
+
depth
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
return best?.project;
|
|
1595
|
+
}
|
|
1596
|
+
async function gitInfo(dir) {
|
|
1597
|
+
try {
|
|
1598
|
+
const { stdout } = await run$2("git", [
|
|
1599
|
+
"-C",
|
|
1600
|
+
dir,
|
|
1601
|
+
"rev-parse",
|
|
1602
|
+
"--abbrev-ref",
|
|
1603
|
+
"HEAD",
|
|
1604
|
+
"--show-toplevel",
|
|
1605
|
+
"--path-format=absolute",
|
|
1606
|
+
"--git-common-dir"
|
|
1607
|
+
], {
|
|
1608
|
+
timeout: 3e3,
|
|
1609
|
+
windowsHide: true
|
|
1610
|
+
});
|
|
1611
|
+
const [branch, top, common] = stdout.trim().split("\n");
|
|
1612
|
+
if (!top || !common) return void 0;
|
|
1613
|
+
const realTop = await realpath(top).catch(() => top);
|
|
1614
|
+
const repository = basename(common) === ".git" ? dirname(common) : void 0;
|
|
1615
|
+
const main = repository && await realpath(repository).catch(() => repository);
|
|
1616
|
+
return {
|
|
1617
|
+
branch: branch && branch !== "HEAD" ? branch : void 0,
|
|
1618
|
+
top: realTop,
|
|
1619
|
+
main: main && main !== realTop ? main : void 0
|
|
1620
|
+
};
|
|
1621
|
+
} catch {
|
|
1622
|
+
return;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
//#endregion
|
|
1626
|
+
//#region ../provider-ensemble/src/projects.ts
|
|
1627
|
+
const ROOT_PREFIX = "ensemble://thread/";
|
|
1628
|
+
/** The project root Tencil uses for an Ensemble thread: `ensemble://thread/<id>`. */
|
|
1629
|
+
function ensembleRoot(threadId) {
|
|
1630
|
+
return `${ROOT_PREFIX}${encodeURIComponent(threadId)}`;
|
|
1631
|
+
}
|
|
1632
|
+
/** The thread an `ensemble://thread/<id>` root names; undefined for a folder. */
|
|
1633
|
+
function ensembleThreadId(root) {
|
|
1634
|
+
return root.startsWith(ROOT_PREFIX) ? decodeURIComponent(root.slice(18)) : void 0;
|
|
1635
|
+
}
|
|
1636
|
+
/** Open Ensemble threads for the project picker, forwarded ones included; [] until paired. */
|
|
1637
|
+
async function listEnsembleProjects(options = {}) {
|
|
1638
|
+
return (await (await pairedClient(options))?.threads() ?? []).map((thread) => ({
|
|
1639
|
+
workspaceRoot: ensembleRoot(thread.id),
|
|
1640
|
+
title: thread.title
|
|
1641
|
+
}));
|
|
1642
|
+
}
|
|
1643
|
+
/** The root of the Ensemble thread whose dev server listens on `port`, when there is one. */
|
|
1644
|
+
async function ensembleProjectForPort(port, options = {}) {
|
|
1645
|
+
const threads = await (await pairedClient(options))?.threads({ port }) ?? [];
|
|
1646
|
+
return threads.length === 1 && threads[0] ? ensembleRoot(threads[0].id) : void 0;
|
|
1647
|
+
}
|
|
1648
|
+
async function pairedClient(options) {
|
|
1649
|
+
const baseUrl = options.baseUrl ?? ensembleUrl();
|
|
1650
|
+
const token = await (options.credentials ?? new EnsembleCredentialStore()).get(baseUrl);
|
|
1651
|
+
return token ? new EnsembleClient({
|
|
1652
|
+
baseUrl,
|
|
1653
|
+
token,
|
|
1654
|
+
timeoutMs: 1500
|
|
1655
|
+
}) : void 0;
|
|
1656
|
+
}
|
|
1657
|
+
//#endregion
|
|
1658
|
+
//#region ../provider-ensemble/src/thread-feed.ts
|
|
1659
|
+
/**
|
|
1660
|
+
* One Ensemble thread's feed, shared by every pin in it. It keeps each chat's state,
|
|
1661
|
+
* so a watcher that starts late gets it replayed, and resumes from the last event
|
|
1662
|
+
* after a drop.
|
|
1663
|
+
*/
|
|
1664
|
+
var ThreadFeed = class {
|
|
1665
|
+
threadId;
|
|
1666
|
+
options;
|
|
1667
|
+
#chats = /* @__PURE__ */ new Map();
|
|
1668
|
+
#watchers = /* @__PURE__ */ new Map();
|
|
1669
|
+
#cursor;
|
|
1670
|
+
#following;
|
|
1671
|
+
#archived = false;
|
|
1672
|
+
constructor(threadId, options) {
|
|
1673
|
+
this.threadId = threadId;
|
|
1674
|
+
this.options = options;
|
|
1675
|
+
}
|
|
1676
|
+
get watched() {
|
|
1677
|
+
return this.#watchers.size > 0;
|
|
1678
|
+
}
|
|
1679
|
+
/** Replay the chat's state to `sink`, then send it live updates. Call `follow` to go live. */
|
|
1680
|
+
watch(chatId, sink) {
|
|
1681
|
+
if (this.#archived) {
|
|
1682
|
+
sink.gone();
|
|
1683
|
+
return () => {};
|
|
1684
|
+
}
|
|
1685
|
+
const watchers = this.#watchers.get(chatId) ?? /* @__PURE__ */ new Set();
|
|
1686
|
+
this.#watchers.set(chatId, watchers);
|
|
1687
|
+
watchers.add(sink);
|
|
1688
|
+
const chat = this.#chats.get(chatId);
|
|
1689
|
+
if (chat) replay(chat, sink);
|
|
1690
|
+
return () => {
|
|
1691
|
+
watchers.delete(sink);
|
|
1692
|
+
if (!watchers.size) this.#watchers.delete(chatId);
|
|
1693
|
+
if (!this.watched) this.stop();
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
/** Follow the feed while anyone watches; does nothing when it already does. */
|
|
1697
|
+
follow(client) {
|
|
1698
|
+
if (this.#following || this.#archived || !this.watched) return;
|
|
1699
|
+
const following = new AbortController();
|
|
1700
|
+
this.#following = following;
|
|
1701
|
+
this.#follow(client, following.signal).finally(() => {
|
|
1702
|
+
if (this.#following === following) this.#following = void 0;
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
stop() {
|
|
1706
|
+
this.#following?.abort();
|
|
1707
|
+
this.#following = void 0;
|
|
1708
|
+
}
|
|
1709
|
+
async #follow(client, signal) {
|
|
1710
|
+
const minMs = this.options.timeouts?.reconnectMinMs ?? 1e3;
|
|
1711
|
+
const maxMs = this.options.timeouts?.reconnectMaxMs ?? 3e4;
|
|
1712
|
+
let delayMs = minMs;
|
|
1713
|
+
while (!signal.aborted) {
|
|
1714
|
+
try {
|
|
1715
|
+
const events = client.feed(this.threadId, {
|
|
1716
|
+
after: this.#cursor,
|
|
1717
|
+
signal,
|
|
1718
|
+
silenceMs: this.options.timeouts?.silenceMs
|
|
1719
|
+
});
|
|
1720
|
+
for await (const { id, event } of events) {
|
|
1721
|
+
this.#apply(event);
|
|
1722
|
+
if (id !== void 0) this.#cursor = id;
|
|
1723
|
+
delayMs = minMs;
|
|
1724
|
+
}
|
|
1725
|
+
} catch (error) {
|
|
1726
|
+
if (signal.aborted) return;
|
|
1727
|
+
if (error instanceof EnsembleUnauthorizedError) return this.options.onUnauthorized();
|
|
1728
|
+
if (error instanceof EnsembleHttpError && error.status === 404) return this.#apply({
|
|
1729
|
+
type: "archived",
|
|
1730
|
+
threadId: this.threadId
|
|
1731
|
+
});
|
|
1732
|
+
this.options.log?.(`Reconnecting to Ensemble's feed: ${errorMessage$2(error)}`);
|
|
1733
|
+
}
|
|
1734
|
+
await setTimeout$1(delayMs, void 0, {
|
|
1735
|
+
signal,
|
|
1736
|
+
ref: false
|
|
1737
|
+
}).catch(() => {});
|
|
1738
|
+
delayMs = Math.min(delayMs * 2, maxMs);
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
#apply(event) {
|
|
1742
|
+
switch (event.type) {
|
|
1743
|
+
case "archived":
|
|
1744
|
+
this.#archived = true;
|
|
1745
|
+
this.stop();
|
|
1746
|
+
for (const sinks of this.#watchers.values()) for (const sink of sinks) sink.gone();
|
|
1747
|
+
return;
|
|
1748
|
+
case "chat":
|
|
1749
|
+
this.#upsertMessages(event.chatId, event.messages);
|
|
1750
|
+
this.#replaceSteps(event.chatId, event.steps);
|
|
1751
|
+
this.#setStatus(event.chatId, event.status);
|
|
1752
|
+
return;
|
|
1753
|
+
case "message":
|
|
1754
|
+
this.#upsertMessages(event.chatId, [event.message]);
|
|
1755
|
+
return;
|
|
1756
|
+
case "steps":
|
|
1757
|
+
this.#replaceSteps(event.chatId, event.steps);
|
|
1758
|
+
return;
|
|
1759
|
+
case "status":
|
|
1760
|
+
this.#setStatus(event.chatId, event.status);
|
|
1761
|
+
return;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
#upsertMessages(chatId, messages) {
|
|
1765
|
+
const chat = this.#chat(chatId);
|
|
1766
|
+
for (const message of messages) {
|
|
1767
|
+
const createdAt = chat.messages.get(message.id)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1768
|
+
const next = {
|
|
1769
|
+
...message,
|
|
1770
|
+
createdAt
|
|
1771
|
+
};
|
|
1772
|
+
chat.messages.set(message.id, next);
|
|
1773
|
+
for (const sink of this.#sinks(chatId)) sink.message(next);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
/** Ensemble sends the turn's whole list of steps each time. */
|
|
1777
|
+
#replaceSteps(chatId, steps) {
|
|
1778
|
+
const chat = this.#chat(chatId);
|
|
1779
|
+
const previous = chat.steps;
|
|
1780
|
+
chat.steps = /* @__PURE__ */ new Map();
|
|
1781
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1782
|
+
for (const step of steps) {
|
|
1783
|
+
const before = previous.get(step.id);
|
|
1784
|
+
const next = {
|
|
1785
|
+
...step,
|
|
1786
|
+
startedAt: before?.startedAt ?? now,
|
|
1787
|
+
...step.status === "running" ? {} : { endedAt: before?.endedAt ?? now }
|
|
1788
|
+
};
|
|
1789
|
+
chat.steps.set(step.id, next);
|
|
1790
|
+
for (const sink of this.#sinks(chatId)) sink.step?.(next);
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
#setStatus(chatId, status) {
|
|
1794
|
+
this.#chat(chatId).status = status;
|
|
1795
|
+
for (const sink of this.#sinks(chatId)) sink.status(status);
|
|
1796
|
+
}
|
|
1797
|
+
#chat(chatId) {
|
|
1798
|
+
let chat = this.#chats.get(chatId);
|
|
1799
|
+
if (!chat) {
|
|
1800
|
+
chat = {
|
|
1801
|
+
messages: /* @__PURE__ */ new Map(),
|
|
1802
|
+
steps: /* @__PURE__ */ new Map()
|
|
1803
|
+
};
|
|
1804
|
+
this.#chats.set(chatId, chat);
|
|
1805
|
+
}
|
|
1806
|
+
return chat;
|
|
1807
|
+
}
|
|
1808
|
+
#sinks(chatId) {
|
|
1809
|
+
return this.#watchers.get(chatId) ?? [];
|
|
1810
|
+
}
|
|
1811
|
+
};
|
|
1812
|
+
function replay(chat, sink) {
|
|
1813
|
+
for (const message of chat.messages.values()) sink.message(message);
|
|
1814
|
+
for (const step of chat.steps.values()) sink.step?.(step);
|
|
1815
|
+
if (chat.status) sink.status(chat.status);
|
|
1816
|
+
}
|
|
1817
|
+
//#endregion
|
|
1818
|
+
//#region ../provider-ensemble/src/ensemble-provider.ts
|
|
1819
|
+
/**
|
|
1820
|
+
* Sends pins to the Ensemble thread serving the page, one chat per pin, through
|
|
1821
|
+
* Ensemble's public local API. A page served from an Ensemble project's own folder
|
|
1822
|
+
* starts a thread per pin instead. Pins in a thread share one feed.
|
|
1823
|
+
*/
|
|
1824
|
+
var EnsembleProvider = class {
|
|
1825
|
+
options;
|
|
1826
|
+
id = "ensemble";
|
|
1827
|
+
label = "Ensemble";
|
|
1828
|
+
#baseUrl;
|
|
1829
|
+
#target;
|
|
1830
|
+
#credentials;
|
|
1831
|
+
#feeds = /* @__PURE__ */ new Map();
|
|
1832
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
1833
|
+
#info = {
|
|
1834
|
+
id: "ensemble",
|
|
1835
|
+
label: "Ensemble",
|
|
1836
|
+
state: "connecting"
|
|
1837
|
+
};
|
|
1838
|
+
/** Set while Ensemble accepts the token and the thread is open. */
|
|
1839
|
+
#client;
|
|
1840
|
+
#starting;
|
|
1841
|
+
#pairing;
|
|
1842
|
+
#retry;
|
|
1843
|
+
#disposed = false;
|
|
1844
|
+
constructor(options) {
|
|
1845
|
+
this.options = options;
|
|
1846
|
+
this.#baseUrl = new URL(options.baseUrl ?? ensembleUrl()).origin;
|
|
1847
|
+
const threadId = ensembleThreadId(options.projectRoot);
|
|
1848
|
+
if (threadId) this.#target = {
|
|
1849
|
+
kind: "thread",
|
|
1850
|
+
threadId
|
|
1851
|
+
};
|
|
1852
|
+
this.#credentials = options.credentials ?? new EnsembleCredentialStore();
|
|
1853
|
+
}
|
|
1854
|
+
info() {
|
|
1855
|
+
return this.#info;
|
|
1856
|
+
}
|
|
1857
|
+
onInfoChange(listener) {
|
|
1858
|
+
this.#listeners.add(listener);
|
|
1859
|
+
return () => this.#listeners.delete(listener);
|
|
1860
|
+
}
|
|
1861
|
+
start() {
|
|
1862
|
+
this.#starting ??= this.#connect().finally(() => {
|
|
1863
|
+
this.#starting = void 0;
|
|
1864
|
+
});
|
|
1865
|
+
return this.#starting;
|
|
1866
|
+
}
|
|
1867
|
+
/** Ask the user to allow Tencil in Ensemble, then connect with the new token. */
|
|
1868
|
+
pair() {
|
|
1869
|
+
this.#pairing ??= this.#pair().finally(() => {
|
|
1870
|
+
this.#pairing = void 0;
|
|
1871
|
+
});
|
|
1872
|
+
return this.#pairing;
|
|
1873
|
+
}
|
|
1874
|
+
async listThreads() {
|
|
1875
|
+
const target = await this.#requireTarget();
|
|
1876
|
+
const [name, threads] = target.kind === "thread" ? await this.#call(async (client) => {
|
|
1877
|
+
const thread = await client.thread(target.threadId);
|
|
1878
|
+
return [thread.title, [thread]];
|
|
1879
|
+
}) : [target.project.name, await this.#call((client) => client.threads({ project: target.project.id }))];
|
|
1880
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1881
|
+
return {
|
|
1882
|
+
project: { name },
|
|
1883
|
+
threads: threads.flatMap((thread) => thread.chats.map((chat) => {
|
|
1884
|
+
const id = chatThreadId(thread.id, chat.id);
|
|
1885
|
+
return {
|
|
1886
|
+
id,
|
|
1887
|
+
title: chat.title,
|
|
1888
|
+
status: chat.status,
|
|
1889
|
+
updatedAt,
|
|
1890
|
+
url: this.threadUrl(id)
|
|
1891
|
+
};
|
|
1892
|
+
}))
|
|
1893
|
+
};
|
|
1894
|
+
}
|
|
1895
|
+
threadUrl(providerThreadId) {
|
|
1896
|
+
return ensembleRoot(parseChatThreadId(providerThreadId).threadId);
|
|
1897
|
+
}
|
|
1898
|
+
async createThread(input) {
|
|
1899
|
+
const target = await this.#requireTarget();
|
|
1900
|
+
const chat = {
|
|
1901
|
+
title: input.title,
|
|
1902
|
+
prompt: input.text,
|
|
1903
|
+
attachments: input.attachments.map(toEnsembleImage),
|
|
1904
|
+
...input.model ? { model: input.model } : {}
|
|
1905
|
+
};
|
|
1906
|
+
const providerThreadId = target.kind === "thread" ? chatThreadId(target.threadId, (await this.#call((client) => client.createChat(target.threadId, chat))).id) : await this.#call(async (client) => {
|
|
1907
|
+
const thread = await client.createThread({
|
|
1908
|
+
projectId: target.project.id,
|
|
1909
|
+
...chat
|
|
1910
|
+
});
|
|
1911
|
+
return chatThreadId(thread.id, thread.chats[0]?.id ?? "main");
|
|
1912
|
+
});
|
|
1913
|
+
return {
|
|
1914
|
+
providerThreadId,
|
|
1915
|
+
url: this.threadUrl(providerThreadId),
|
|
1916
|
+
archivable: target.kind === "project"
|
|
1917
|
+
};
|
|
1918
|
+
}
|
|
1919
|
+
async archive(providerThreadId) {
|
|
1920
|
+
const { threadId, chatId } = parseChatThreadId(providerThreadId);
|
|
1921
|
+
await this.#call(async (client) => {
|
|
1922
|
+
if ((await client.thread(threadId)).chats.some((chat) => chat.id !== chatId)) return;
|
|
1923
|
+
await client.archiveThread(threadId);
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1926
|
+
async reopen(providerThreadId) {
|
|
1927
|
+
const { threadId } = parseChatThreadId(providerThreadId);
|
|
1928
|
+
await this.#call((client) => client.reopenThread(threadId));
|
|
1929
|
+
}
|
|
1930
|
+
async sendMessage(input) {
|
|
1931
|
+
const { threadId, chatId } = parseChatThreadId(input.providerThreadId);
|
|
1932
|
+
await this.#call((client) => client.sendMessage(threadId, chatId, {
|
|
1933
|
+
text: input.text,
|
|
1934
|
+
attachments: input.attachments.map(toEnsembleImage)
|
|
1935
|
+
}));
|
|
1936
|
+
}
|
|
1937
|
+
async interrupt(providerThreadId) {
|
|
1938
|
+
const { threadId, chatId } = parseChatThreadId(providerThreadId);
|
|
1939
|
+
await this.#call((client) => client.stop(threadId, chatId));
|
|
1940
|
+
}
|
|
1941
|
+
watch(providerThreadId, sink) {
|
|
1942
|
+
const { threadId, chatId } = parseChatThreadId(providerThreadId);
|
|
1943
|
+
let feed = this.#feeds.get(threadId);
|
|
1944
|
+
if (!feed) {
|
|
1945
|
+
feed = new ThreadFeed(threadId, {
|
|
1946
|
+
onUnauthorized: () => this.#unauthorized(),
|
|
1947
|
+
log: this.options.log,
|
|
1948
|
+
timeouts: this.options.timeouts
|
|
1949
|
+
});
|
|
1950
|
+
this.#feeds.set(threadId, feed);
|
|
1951
|
+
}
|
|
1952
|
+
const unwatch = feed.watch(chatId, sink);
|
|
1953
|
+
if (this.#client) feed.follow(this.#client);
|
|
1954
|
+
return () => {
|
|
1955
|
+
unwatch();
|
|
1956
|
+
if (!feed.watched) this.#feeds.delete(threadId);
|
|
1957
|
+
};
|
|
1958
|
+
}
|
|
1959
|
+
async dispose() {
|
|
1960
|
+
this.#disposed = true;
|
|
1961
|
+
clearTimeout(this.#retry);
|
|
1962
|
+
for (const feed of this.#feeds.values()) feed.stop();
|
|
1963
|
+
this.#feeds.clear();
|
|
1964
|
+
}
|
|
1965
|
+
async #connect() {
|
|
1966
|
+
clearTimeout(this.#retry);
|
|
1967
|
+
if (!await new EnsembleClient({ baseUrl: this.#baseUrl }).isRunning()) return this.#retryLater("Ensemble isn't running. Open the Ensemble app.");
|
|
1968
|
+
const token = await this.#credentials.get(this.#baseUrl);
|
|
1969
|
+
if (!token) return this.#unauthorized();
|
|
1970
|
+
const client = new EnsembleClient({
|
|
1971
|
+
baseUrl: this.#baseUrl,
|
|
1972
|
+
token,
|
|
1973
|
+
timeoutMs: this.options.timeouts?.requestMs
|
|
1974
|
+
});
|
|
1975
|
+
try {
|
|
1976
|
+
let target = this.#target;
|
|
1977
|
+
if (!target) {
|
|
1978
|
+
const found = await targetForFolder(client, this.options.projectRoot);
|
|
1979
|
+
if (found.kind === "missing") return this.#retryLater(`${basename(found.repository)} isn't in Ensemble yet. Add ${tildify(found.repository)} as a project in Ensemble.`);
|
|
1980
|
+
target = found;
|
|
1981
|
+
}
|
|
1982
|
+
const label = target.kind === "thread" ? (await client.thread(target.threadId)).title : `${target.project.name} · new thread per pin`;
|
|
1983
|
+
if (this.#disposed) return;
|
|
1984
|
+
this.#target = target;
|
|
1985
|
+
this.#client = client;
|
|
1986
|
+
this.#setInfo({
|
|
1987
|
+
state: "ready",
|
|
1988
|
+
target: label
|
|
1989
|
+
});
|
|
1990
|
+
for (const feed of this.#feeds.values()) feed.follow(client);
|
|
1991
|
+
} catch (error) {
|
|
1992
|
+
if (error instanceof EnsembleUnauthorizedError) return this.#unauthorized();
|
|
1993
|
+
if (error instanceof EnsembleHttpError && error.status === 404) return this.#setInfo({
|
|
1994
|
+
state: "unavailable",
|
|
1995
|
+
detail: "This Ensemble thread is closed. Choose an open one."
|
|
1996
|
+
});
|
|
1997
|
+
this.#retryLater(`Ensemble didn't answer: ${errorMessage$2(error)}`);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
async #pair() {
|
|
2001
|
+
this.#setInfo({
|
|
2002
|
+
state: "connecting",
|
|
2003
|
+
detail: "Allow Tencil in the Ensemble app."
|
|
2004
|
+
});
|
|
2005
|
+
try {
|
|
2006
|
+
const token = await new EnsembleClient({ baseUrl: this.#baseUrl }).connect();
|
|
2007
|
+
await this.#credentials.set(this.#baseUrl, token);
|
|
2008
|
+
} catch (error) {
|
|
2009
|
+
this.#setInfo({
|
|
2010
|
+
state: "unauthorized",
|
|
2011
|
+
canPair: true,
|
|
2012
|
+
detail: errorMessage$2(error)
|
|
2013
|
+
});
|
|
2014
|
+
throw error;
|
|
2015
|
+
}
|
|
2016
|
+
await this.#starting;
|
|
2017
|
+
await this.start();
|
|
2018
|
+
}
|
|
2019
|
+
/** Run a call once connected; a refused token asks the user to pair again. */
|
|
2020
|
+
async #call(call) {
|
|
2021
|
+
if (!this.#client) await this.start();
|
|
2022
|
+
const client = this.#client;
|
|
2023
|
+
if (!client) throw new Error(this.#info.detail ?? "Not connected to Ensemble");
|
|
2024
|
+
try {
|
|
2025
|
+
return await call(client);
|
|
2026
|
+
} catch (error) {
|
|
2027
|
+
if (error instanceof EnsembleUnauthorizedError) this.#unauthorized();
|
|
2028
|
+
throw error;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
async #requireTarget() {
|
|
2032
|
+
if (!this.#target) await this.start();
|
|
2033
|
+
if (!this.#target) throw new Error(this.#info.detail ?? "Not connected to Ensemble");
|
|
2034
|
+
return this.#target;
|
|
2035
|
+
}
|
|
2036
|
+
#unauthorized() {
|
|
2037
|
+
this.#client = void 0;
|
|
2038
|
+
for (const feed of this.#feeds.values()) feed.stop();
|
|
2039
|
+
this.#setInfo({
|
|
2040
|
+
state: "unauthorized",
|
|
2041
|
+
canPair: true,
|
|
2042
|
+
detail: "Not connected to Ensemble. Pair, then allow Tencil in the Ensemble app."
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
#retryLater(detail) {
|
|
2046
|
+
this.#client = void 0;
|
|
2047
|
+
this.#setInfo({
|
|
2048
|
+
state: "unavailable",
|
|
2049
|
+
detail
|
|
2050
|
+
});
|
|
2051
|
+
if (this.#disposed) return;
|
|
2052
|
+
this.#retry = setTimeout(() => void this.start(), this.options.timeouts?.retryMs ?? 5e3);
|
|
2053
|
+
this.#retry.unref?.();
|
|
2054
|
+
}
|
|
2055
|
+
#setInfo(next) {
|
|
2056
|
+
if (this.#disposed) return;
|
|
2057
|
+
this.#info = {
|
|
2058
|
+
id: this.id,
|
|
2059
|
+
label: this.label,
|
|
2060
|
+
...next
|
|
2061
|
+
};
|
|
2062
|
+
for (const listener of this.#listeners) listener(this.#info);
|
|
2063
|
+
}
|
|
2064
|
+
};
|
|
2065
|
+
/** A pin's id is its Ensemble thread and chat: `<threadId>/<chatId>`. */
|
|
2066
|
+
function chatThreadId(threadId, chatId) {
|
|
2067
|
+
return `${threadId}/${chatId}`;
|
|
2068
|
+
}
|
|
2069
|
+
function parseChatThreadId(providerThreadId) {
|
|
2070
|
+
const [threadId, chatId, ...rest] = providerThreadId.split("/");
|
|
2071
|
+
if (!threadId || !chatId || rest.length) throw new Error(`Not an Ensemble chat: ${providerThreadId}`);
|
|
2072
|
+
return {
|
|
2073
|
+
threadId,
|
|
2074
|
+
chatId
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
function tildify(path) {
|
|
2078
|
+
const home = homedir();
|
|
2079
|
+
return path === home || path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
|
|
2080
|
+
}
|
|
2081
|
+
function toEnsembleImage(image) {
|
|
2082
|
+
return {
|
|
2083
|
+
name: image.name,
|
|
2084
|
+
mediaType: image.mimeType,
|
|
2085
|
+
data: image.dataUrl.slice(image.dataUrl.indexOf(",") + 1)
|
|
2086
|
+
};
|
|
2087
|
+
}
|
|
1213
2088
|
//#endregion
|
|
1214
2089
|
//#region src/daemon/project-resolver.ts
|
|
1215
2090
|
const run$1 = promisify(execFile);
|
|
@@ -1217,52 +2092,126 @@ const defaultExec = async (command, args) => (await run$1(command, args, {
|
|
|
1217
2092
|
timeout: 3e3,
|
|
1218
2093
|
windowsHide: true
|
|
1219
2094
|
})).stdout;
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
* 2. the repository root the Vite or Next loader sent, if it's a git checkout,
|
|
1224
|
-
* 3. the dev server's working directory, found from the port it listens on.
|
|
1225
|
-
* Returns undefined when neither works; the overlay then asks.
|
|
1226
|
-
*/
|
|
2095
|
+
function pickKey(origin, detected) {
|
|
2096
|
+
return `${origin} ${detected}`;
|
|
2097
|
+
}
|
|
1227
2098
|
var ProjectResolver = class {
|
|
1228
2099
|
#memory;
|
|
2100
|
+
/** Picks made over a detected project, by address and that project. */
|
|
2101
|
+
#picks;
|
|
1229
2102
|
#exec;
|
|
1230
2103
|
#platform;
|
|
2104
|
+
#ensembleForPort;
|
|
1231
2105
|
constructor(options) {
|
|
1232
2106
|
this.#memory = new OriginMemory(join(options.dataDir, "origins.json"));
|
|
2107
|
+
this.#picks = new OriginMemory(join(options.dataDir, "project-picks.json"));
|
|
1233
2108
|
this.#exec = options.exec ?? defaultExec;
|
|
1234
2109
|
this.#platform = options.platform ?? process.platform;
|
|
2110
|
+
this.#ensembleForPort = options.ensembleForPort;
|
|
1235
2111
|
}
|
|
1236
2112
|
async resolve(pageUrl, claimedRoot) {
|
|
2113
|
+
return (await this.detect(pageUrl, claimedRoot))?.root;
|
|
2114
|
+
}
|
|
2115
|
+
/**
|
|
2116
|
+
* The page's project and how it was found. A pick made over a detected
|
|
2117
|
+
* project only holds while that same project is detected on the address:
|
|
2118
|
+
* when another app takes the port, detection wins again.
|
|
2119
|
+
*/
|
|
2120
|
+
async detect(pageUrl, claimedRoot) {
|
|
1237
2121
|
const origin = safeOrigin(pageUrl);
|
|
1238
2122
|
if (!origin) return void 0;
|
|
2123
|
+
const found = await this.#automatic(origin, claimedRoot);
|
|
2124
|
+
if (found) {
|
|
2125
|
+
const picked = await this.#picks.get(pickKey(origin, found.root));
|
|
2126
|
+
if (!(picked && (ensembleThreadId(picked) || existsSync(picked))) || picked === found.root) return found;
|
|
2127
|
+
return {
|
|
2128
|
+
root: picked,
|
|
2129
|
+
source: {
|
|
2130
|
+
via: "picked",
|
|
2131
|
+
detected: {
|
|
2132
|
+
root: found.root,
|
|
2133
|
+
...found.source
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
};
|
|
2137
|
+
}
|
|
1239
2138
|
const remembered = await this.#memory.get(origin);
|
|
1240
|
-
|
|
1241
|
-
|
|
2139
|
+
return remembered && (ensembleThreadId(remembered) || existsSync(remembered)) ? {
|
|
2140
|
+
root: remembered,
|
|
2141
|
+
source: { via: "picked" }
|
|
2142
|
+
} : void 0;
|
|
2143
|
+
}
|
|
2144
|
+
/** Detection alone: Ensemble thread, the plugin's git root, then the port. */
|
|
2145
|
+
async #automatic(origin, claimedRoot) {
|
|
1242
2146
|
const port = portOf(origin);
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
2147
|
+
const thread = port ? await this.#ensembleForPort?.(port).catch(() => void 0) : void 0;
|
|
2148
|
+
if (thread) return {
|
|
2149
|
+
root: thread,
|
|
2150
|
+
source: {
|
|
2151
|
+
via: "ensemble",
|
|
2152
|
+
port
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
if (claimedRoot && isGitRoot(claimedRoot)) return {
|
|
2156
|
+
root: resolve(claimedRoot),
|
|
2157
|
+
source: { via: "plugin" }
|
|
2158
|
+
};
|
|
2159
|
+
const found = port ? await this.#portFolder(port).catch(() => void 0) : void 0;
|
|
2160
|
+
if (!found || !port) return void 0;
|
|
2161
|
+
return {
|
|
2162
|
+
root: projectRoot(found.folder),
|
|
2163
|
+
source: {
|
|
2164
|
+
via: found.docker ? "docker" : "port",
|
|
2165
|
+
port
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Use `root` for this address while `detected` is what Tencil finds there
|
|
2171
|
+
* (the overlay's Change). Picking the detected project itself undoes it.
|
|
2172
|
+
*/
|
|
2173
|
+
async pick(pageUrl, detected, root) {
|
|
2174
|
+
const origin = safeOrigin(pageUrl);
|
|
2175
|
+
if (!origin) return;
|
|
2176
|
+
const key = pickKey(origin, detected);
|
|
2177
|
+
if (projectKey(root) === detected) await this.#picks.delete(key);
|
|
2178
|
+
else await this.#picks.set(key, projectKey(root));
|
|
1246
2179
|
}
|
|
1247
2180
|
/** Remember the user's choice for an address (from the overlay's project picker). */
|
|
1248
2181
|
remember(pageUrl, root) {
|
|
1249
2182
|
const origin = safeOrigin(pageUrl);
|
|
1250
|
-
return origin ? this.#memory.set(origin,
|
|
2183
|
+
return origin ? this.#memory.set(origin, projectKey(root)) : Promise.resolve();
|
|
1251
2184
|
}
|
|
1252
2185
|
/**
|
|
1253
2186
|
* Folder of the process listening on `port`: its working directory, or its script's
|
|
1254
2187
|
* package. When Docker publishes the port, the compose project of the container.
|
|
1255
2188
|
*/
|
|
1256
2189
|
async folderForPort(port) {
|
|
2190
|
+
return (await this.#portFolder(port))?.folder;
|
|
2191
|
+
}
|
|
2192
|
+
async #portFolder(port) {
|
|
2193
|
+
const docker = async () => {
|
|
2194
|
+
const folder = await this.#composeFolder(port);
|
|
2195
|
+
return folder ? {
|
|
2196
|
+
folder,
|
|
2197
|
+
docker: true
|
|
2198
|
+
} : void 0;
|
|
2199
|
+
};
|
|
1257
2200
|
const pids = await this.#listeners(port);
|
|
1258
|
-
if (pids.length === 0 && this.#platform === "linux") return
|
|
2201
|
+
if (pids.length === 0 && this.#platform === "linux") return docker();
|
|
1259
2202
|
for (const pid of pids) {
|
|
1260
2203
|
const cwd = await this.#cwd(pid).catch(() => void 0);
|
|
1261
|
-
if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return
|
|
2204
|
+
if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return {
|
|
2205
|
+
folder: cwd,
|
|
2206
|
+
docker: false
|
|
2207
|
+
};
|
|
1262
2208
|
const commandLine = await this.#commandLine(pid).catch(() => "");
|
|
1263
|
-
if (isDockerForwarder(commandLine)) return
|
|
2209
|
+
if (isDockerForwarder(commandLine)) return docker();
|
|
1264
2210
|
const fromCommand = projectFromCommandLine(commandLine);
|
|
1265
|
-
if (fromCommand) return
|
|
2211
|
+
if (fromCommand) return {
|
|
2212
|
+
folder: fromCommand,
|
|
2213
|
+
docker: false
|
|
2214
|
+
};
|
|
1266
2215
|
}
|
|
1267
2216
|
}
|
|
1268
2217
|
/** Working directory of the compose project whose container publishes `port`. */
|
|
@@ -1276,11 +2225,7 @@ var ProjectResolver = class {
|
|
|
1276
2225
|
]).catch(() => ""));
|
|
1277
2226
|
}
|
|
1278
2227
|
async #listeners(port) {
|
|
1279
|
-
if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", [
|
|
1280
|
-
"-ano",
|
|
1281
|
-
"-p",
|
|
1282
|
-
"TCP"
|
|
1283
|
-
]), port);
|
|
2228
|
+
if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", ["-ano"]), port);
|
|
1284
2229
|
try {
|
|
1285
2230
|
return parsePids(await this.#exec("lsof", [
|
|
1286
2231
|
"-nP",
|
|
@@ -1327,6 +2272,10 @@ var ProjectResolver = class {
|
|
|
1327
2272
|
function isGitRoot(folder) {
|
|
1328
2273
|
return isAbsolute(folder) && existsSync(join(folder, ".git"));
|
|
1329
2274
|
}
|
|
2275
|
+
/** How the daemon keys a project: an `ensemble://thread/<id>` root as is, a folder by its absolute path. */
|
|
2276
|
+
function projectKey(root) {
|
|
2277
|
+
return ensembleThreadId(root) === void 0 ? resolve(root) : root;
|
|
2278
|
+
}
|
|
1330
2279
|
/** Closest folder with a package.json at or above `folder`, or `folder` itself. */
|
|
1331
2280
|
function projectRoot(folder) {
|
|
1332
2281
|
let dir = resolve(folder);
|
|
@@ -1397,6 +2346,15 @@ var OriginMemory = class {
|
|
|
1397
2346
|
async set(origin, root) {
|
|
1398
2347
|
const all = await this.#read();
|
|
1399
2348
|
all[origin] = root;
|
|
2349
|
+
await this.#write(all);
|
|
2350
|
+
}
|
|
2351
|
+
async delete(origin) {
|
|
2352
|
+
const all = await this.#read();
|
|
2353
|
+
if (!(origin in all)) return;
|
|
2354
|
+
delete all[origin];
|
|
2355
|
+
await this.#write(all);
|
|
2356
|
+
}
|
|
2357
|
+
async #write(all) {
|
|
1400
2358
|
await mkdir(dirname(this.path), { recursive: true });
|
|
1401
2359
|
await writeFile(this.path, `${JSON.stringify(all, null, 2)}\n`);
|
|
1402
2360
|
}
|
|
@@ -3301,7 +4259,7 @@ function errorMessage(error) {
|
|
|
3301
4259
|
}
|
|
3302
4260
|
//#endregion
|
|
3303
4261
|
//#region src/version.ts
|
|
3304
|
-
const VERSION = "0.
|
|
4262
|
+
const VERSION = "0.10.0";
|
|
3305
4263
|
//#endregion
|
|
3306
4264
|
//#region src/daemon/thread-store.ts
|
|
3307
4265
|
const StoreFile = z.object({
|
|
@@ -3320,7 +4278,7 @@ function defaultDataDir() {
|
|
|
3320
4278
|
* shared between two bridges.
|
|
3321
4279
|
*/
|
|
3322
4280
|
function projectStorePath(projectRoot, dataDir = defaultDataDir()) {
|
|
3323
|
-
const root =
|
|
4281
|
+
const root = projectKey(projectRoot);
|
|
3324
4282
|
const hash = createHash("sha256").update(root).digest("hex").slice(0, 10);
|
|
3325
4283
|
const slug = basename(root).replace(/[^a-z0-9._-]+/gi, "-").slice(0, 40) || "project";
|
|
3326
4284
|
return join(dataDir, "projects", `${slug}-${hash}.json`);
|
|
@@ -3336,7 +4294,7 @@ var FileThreadStore = class {
|
|
|
3336
4294
|
#writeTimer;
|
|
3337
4295
|
#writing = Promise.resolve();
|
|
3338
4296
|
constructor(projectRoot, dataDir) {
|
|
3339
|
-
this.#root =
|
|
4297
|
+
this.#root = projectKey(projectRoot);
|
|
3340
4298
|
this.path = projectStorePath(this.#root, dataDir);
|
|
3341
4299
|
}
|
|
3342
4300
|
async load() {
|
|
@@ -3395,14 +4353,25 @@ var FileThreadStore = class {
|
|
|
3395
4353
|
};
|
|
3396
4354
|
//#endregion
|
|
3397
4355
|
//#region src/daemon/agents.ts
|
|
3398
|
-
const PROVIDERS = [
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
4356
|
+
const PROVIDERS = [
|
|
4357
|
+
"t3code",
|
|
4358
|
+
"claude-code",
|
|
4359
|
+
"ensemble"
|
|
4360
|
+
];
|
|
4361
|
+
const PROVIDER_OPTIONS = [
|
|
4362
|
+
{
|
|
4363
|
+
id: "t3code",
|
|
4364
|
+
label: "T3 Code"
|
|
4365
|
+
},
|
|
4366
|
+
{
|
|
4367
|
+
id: "claude-code",
|
|
4368
|
+
label: "Claude Code"
|
|
4369
|
+
},
|
|
4370
|
+
{
|
|
4371
|
+
id: "ensemble",
|
|
4372
|
+
label: "Ensemble"
|
|
4373
|
+
}
|
|
4374
|
+
];
|
|
3406
4375
|
const providerLabel = (id) => PROVIDER_OPTIONS.find((option) => option.id === id)?.label ?? id;
|
|
3407
4376
|
const SettingsFile$1 = z.object({
|
|
3408
4377
|
version: z.literal(1),
|
|
@@ -3430,23 +4399,33 @@ async function saveProvider(provider, dataDir = defaultDataDir()) {
|
|
|
3430
4399
|
}, null, 2)}\n`);
|
|
3431
4400
|
await rename(`${path}.tmp`, path);
|
|
3432
4401
|
}
|
|
3433
|
-
/**
|
|
4402
|
+
/**
|
|
4403
|
+
* Which agents this machine has: a paired or running T3 Code, an installed
|
|
4404
|
+
* Claude Code, a running Ensemble app.
|
|
4405
|
+
*/
|
|
3434
4406
|
async function detectAgents(options = {}) {
|
|
3435
|
-
const [t3code, claudeCode] = await Promise.all([
|
|
4407
|
+
const [t3code, claudeCode, ensemble] = await Promise.all([
|
|
4408
|
+
hasT3Code(options.t3Url),
|
|
4409
|
+
hasClaudeCode(),
|
|
4410
|
+
hasEnsemble()
|
|
4411
|
+
]);
|
|
3436
4412
|
return {
|
|
3437
4413
|
t3code,
|
|
3438
|
-
"claude-code": claudeCode
|
|
4414
|
+
"claude-code": claudeCode,
|
|
4415
|
+
ensemble
|
|
3439
4416
|
};
|
|
3440
4417
|
}
|
|
3441
4418
|
/**
|
|
3442
4419
|
* The agent for projects that haven't picked one: the saved choice, else the
|
|
3443
|
-
*
|
|
4420
|
+
* first agent found (T3 Code, Claude Code, Ensemble), else T3 Code.
|
|
3444
4421
|
*/
|
|
3445
4422
|
async function machineProvider(options = {}) {
|
|
3446
4423
|
const saved = await savedProvider(options.dataDir);
|
|
3447
4424
|
if (saved) return saved;
|
|
3448
4425
|
const found = await detectAgents(options);
|
|
3449
|
-
|
|
4426
|
+
if (found.t3code) return "t3code";
|
|
4427
|
+
if (found["claude-code"]) return "claude-code";
|
|
4428
|
+
return found.ensemble ? "ensemble" : "t3code";
|
|
3450
4429
|
}
|
|
3451
4430
|
async function hasT3Code(t3Url) {
|
|
3452
4431
|
const store = new CredentialStore();
|
|
@@ -3458,6 +4437,10 @@ async function hasT3Code(t3Url) {
|
|
|
3458
4437
|
return false;
|
|
3459
4438
|
}
|
|
3460
4439
|
}
|
|
4440
|
+
/** Ensemble's app, running now; finding it needs no token. */
|
|
4441
|
+
function hasEnsemble() {
|
|
4442
|
+
return new EnsembleClient().isRunning();
|
|
4443
|
+
}
|
|
3461
4444
|
/** `claude` on the PATH, or its config folder (login services get a bare PATH). */
|
|
3462
4445
|
async function hasClaudeCode() {
|
|
3463
4446
|
const names = process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"];
|
|
@@ -3465,6 +4448,56 @@ async function hasClaudeCode() {
|
|
|
3465
4448
|
return (await Promise.all(candidates.map((path) => access(path).then(() => true, () => false)))).includes(true);
|
|
3466
4449
|
}
|
|
3467
4450
|
//#endregion
|
|
4451
|
+
//#region src/daemon/preferences.ts
|
|
4452
|
+
const PreferencesFile = Preferences.extend({ version: z.literal(1) });
|
|
4453
|
+
function preferencesPath(dataDir = defaultDataDir()) {
|
|
4454
|
+
return join(dataDir, "preferences.json");
|
|
4455
|
+
}
|
|
4456
|
+
/**
|
|
4457
|
+
* The person's overlay preferences (theme, shortcuts), shared by every project
|
|
4458
|
+
* on this machine. One file, next to `settings.json`.
|
|
4459
|
+
*/
|
|
4460
|
+
var FilePreferences = class {
|
|
4461
|
+
path;
|
|
4462
|
+
#cached;
|
|
4463
|
+
/** Saves run one after another, so a quick second change can't land first. */
|
|
4464
|
+
#writing = Promise.resolve();
|
|
4465
|
+
constructor(path = preferencesPath()) {
|
|
4466
|
+
this.path = path;
|
|
4467
|
+
}
|
|
4468
|
+
async load() {
|
|
4469
|
+
if (this.#cached) return this.#cached;
|
|
4470
|
+
const raw = await readFile(this.path, "utf8").catch(() => void 0);
|
|
4471
|
+
let parsed;
|
|
4472
|
+
try {
|
|
4473
|
+
parsed = raw === void 0 ? void 0 : PreferencesFile.safeParse(JSON.parse(raw));
|
|
4474
|
+
} catch {}
|
|
4475
|
+
const { version: _, ...preferences } = parsed?.success ? parsed.data : { version: 1 };
|
|
4476
|
+
this.#cached = preferences;
|
|
4477
|
+
return preferences;
|
|
4478
|
+
}
|
|
4479
|
+
/** Merges `changes` into what's saved and returns the result. */
|
|
4480
|
+
async update(changes) {
|
|
4481
|
+
const next = {
|
|
4482
|
+
...await this.load(),
|
|
4483
|
+
...changes
|
|
4484
|
+
};
|
|
4485
|
+
this.#cached = next;
|
|
4486
|
+
this.#writing = this.#writing.then(() => this.#write(next)).catch(() => {});
|
|
4487
|
+
await this.#writing;
|
|
4488
|
+
return next;
|
|
4489
|
+
}
|
|
4490
|
+
async #write(preferences) {
|
|
4491
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
4492
|
+
const temp = `${this.path}.tmp`;
|
|
4493
|
+
await writeFile(temp, `${JSON.stringify({
|
|
4494
|
+
version: 1,
|
|
4495
|
+
...preferences
|
|
4496
|
+
}, null, 2)}\n`);
|
|
4497
|
+
await rename(temp, this.path);
|
|
4498
|
+
}
|
|
4499
|
+
};
|
|
4500
|
+
//#endregion
|
|
3468
4501
|
//#region src/daemon/project-settings.ts
|
|
3469
4502
|
const SettingsFile = z.object({
|
|
3470
4503
|
version: z.literal(1),
|
|
@@ -4357,12 +5390,16 @@ var Updater = class {
|
|
|
4357
5390
|
const DEFAULT_PORT = 4747;
|
|
4358
5391
|
/** Screenshots ride along as data URLs. */
|
|
4359
5392
|
const MAX_PAYLOAD_BYTES = 33554432;
|
|
4360
|
-
/**
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
5393
|
+
/** The detected project behind a result, also when a pick overrides it. */
|
|
5394
|
+
function automaticPart(found) {
|
|
5395
|
+
if (!found) return void 0;
|
|
5396
|
+
if (found.source.via === "picked") return found.source.detected;
|
|
5397
|
+
return {
|
|
5398
|
+
root: found.root,
|
|
5399
|
+
via: found.source.via,
|
|
5400
|
+
port: found.source.port
|
|
5401
|
+
};
|
|
5402
|
+
}
|
|
4366
5403
|
async function startDaemon(options = {}) {
|
|
4367
5404
|
const port = options.port ?? 4747;
|
|
4368
5405
|
const host = options.host ?? "127.0.0.1";
|
|
@@ -4371,14 +5408,27 @@ async function startDaemon(options = {}) {
|
|
|
4371
5408
|
const knownHosts = knownHostsFor(addresses, allowedOrigins);
|
|
4372
5409
|
const dataDir = options.dataDir ?? defaultDataDir();
|
|
4373
5410
|
const log = options.log ?? (() => {});
|
|
5411
|
+
const ensembleOptions = {
|
|
5412
|
+
baseUrl: options.ensemble?.url,
|
|
5413
|
+
credentials: options.ensemble?.credentials
|
|
5414
|
+
};
|
|
4374
5415
|
const resolver = new ProjectResolver({
|
|
4375
5416
|
dataDir,
|
|
4376
|
-
exec: options.exec
|
|
5417
|
+
exec: options.exec,
|
|
5418
|
+
ensembleForPort: (port) => ensembleProjectForPort(port, ensembleOptions)
|
|
4377
5419
|
});
|
|
4378
|
-
const
|
|
5420
|
+
const detectProject = async (pageUrl, root) => {
|
|
5421
|
+
if (!options.resolveProject) return resolver.detect(pageUrl, root);
|
|
5422
|
+
const found = await options.resolveProject(pageUrl, root);
|
|
5423
|
+
return found ? {
|
|
5424
|
+
root: found,
|
|
5425
|
+
source: { via: "port" }
|
|
5426
|
+
} : void 0;
|
|
5427
|
+
};
|
|
4379
5428
|
const sessions = /* @__PURE__ */ new Map();
|
|
4380
5429
|
const overlayPath = resolveOverlayPath();
|
|
4381
5430
|
let updater;
|
|
5431
|
+
const preferences = new FilePreferences(preferencesPath(dataDir));
|
|
4382
5432
|
const claudeCodeDir = join(dataDir, "claude-code");
|
|
4383
5433
|
const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
|
|
4384
5434
|
const createProvider = options.createProvider ?? ((root, id) => {
|
|
@@ -4389,6 +5439,11 @@ async function startDaemon(options = {}) {
|
|
|
4389
5439
|
installDir: claudeCodeDir,
|
|
4390
5440
|
log: providerLog
|
|
4391
5441
|
});
|
|
5442
|
+
if (id === "ensemble") return new EnsembleProvider({
|
|
5443
|
+
projectRoot: root,
|
|
5444
|
+
...ensembleOptions,
|
|
5445
|
+
log: providerLog
|
|
5446
|
+
});
|
|
4392
5447
|
const { url, token, ...t3 } = options.t3 ?? {};
|
|
4393
5448
|
return new T3CodeProvider({
|
|
4394
5449
|
...t3,
|
|
@@ -4400,16 +5455,16 @@ async function startDaemon(options = {}) {
|
|
|
4400
5455
|
});
|
|
4401
5456
|
});
|
|
4402
5457
|
const session = (root) => {
|
|
4403
|
-
const key =
|
|
5458
|
+
const key = projectKey(root);
|
|
4404
5459
|
let pending = sessions.get(key);
|
|
4405
5460
|
if (!pending) {
|
|
4406
5461
|
pending = (async () => {
|
|
4407
5462
|
const providers = new ProjectProviders({
|
|
4408
5463
|
choices: PROVIDER_OPTIONS,
|
|
4409
|
-
fallback: options.provider ?? await machineProvider({
|
|
5464
|
+
fallback: options.provider ?? (ensembleThreadId(key) === void 0 ? await machineProvider({
|
|
4410
5465
|
dataDir,
|
|
4411
5466
|
t3Url
|
|
4412
|
-
}),
|
|
5467
|
+
}) : "ensemble"),
|
|
4413
5468
|
create: (id) => createProvider(key, id),
|
|
4414
5469
|
settings: new FileProjectSettings(projectSettingsPath(key, dataDir))
|
|
4415
5470
|
});
|
|
@@ -4439,21 +5494,29 @@ async function startDaemon(options = {}) {
|
|
|
4439
5494
|
}
|
|
4440
5495
|
return pending;
|
|
4441
5496
|
};
|
|
4442
|
-
/** Projects
|
|
5497
|
+
/** Projects any agent knows, offered when a page's project can't be worked out. */
|
|
4443
5498
|
const choices = async () => {
|
|
4444
|
-
const [t3, claude] = await Promise.all([
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
5499
|
+
const [t3, claude, ensemble] = await Promise.all([
|
|
5500
|
+
listT3Projects({
|
|
5501
|
+
baseUrl: t3Url,
|
|
5502
|
+
token: options.t3?.token ?? process.env.TENCIL_T3_TOKEN,
|
|
5503
|
+
credentials: options.t3?.credentials
|
|
5504
|
+
}).catch(() => []),
|
|
5505
|
+
listClaudeCodeProjects({ installDir: claudeCodeDir }).catch(() => []),
|
|
5506
|
+
listEnsembleProjects(ensembleOptions).catch(() => [])
|
|
5507
|
+
]);
|
|
4449
5508
|
const byRoot = /* @__PURE__ */ new Map();
|
|
4450
|
-
for (const project of [
|
|
5509
|
+
for (const project of [
|
|
5510
|
+
...t3,
|
|
5511
|
+
...claude,
|
|
5512
|
+
...ensemble
|
|
5513
|
+
]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
|
|
4451
5514
|
root: project.workspaceRoot,
|
|
4452
5515
|
title: project.title
|
|
4453
5516
|
});
|
|
4454
5517
|
return [...byRoot.values()];
|
|
4455
5518
|
};
|
|
4456
|
-
const noChoicesHint = "No projects found. Open this page's project in T3 Code, or run claude in it once.";
|
|
5519
|
+
const noChoicesHint = "No projects found. Open this page's project in T3 Code or Ensemble, or run claude in it once.";
|
|
4457
5520
|
const settled = async () => (await Promise.allSettled(sessions.values())).filter((r) => r.status === "fulfilled").map((r) => r.value);
|
|
4458
5521
|
let statuses = [];
|
|
4459
5522
|
const refreshStatuses = async () => {
|
|
@@ -4521,7 +5584,13 @@ async function startDaemon(options = {}) {
|
|
|
4521
5584
|
let current;
|
|
4522
5585
|
let detach;
|
|
4523
5586
|
let pageUrl = "";
|
|
5587
|
+
/** What detection found for this page, to switch from and back to. */
|
|
5588
|
+
let detected;
|
|
4524
5589
|
let queue = Promise.resolve();
|
|
5590
|
+
preferences.load().then((saved) => client.send({
|
|
5591
|
+
type: "preferences",
|
|
5592
|
+
preferences: saved
|
|
5593
|
+
}));
|
|
4525
5594
|
const attach = async (root, hello) => {
|
|
4526
5595
|
detach?.();
|
|
4527
5596
|
if (current) current.clients--;
|
|
@@ -4535,8 +5604,15 @@ async function startDaemon(options = {}) {
|
|
|
4535
5604
|
if (message.type === "hello") {
|
|
4536
5605
|
pageUrl = message.pageUrl ?? "";
|
|
4537
5606
|
const claimed = typeof message.root === "string" ? message.root : void 0;
|
|
4538
|
-
const
|
|
4539
|
-
|
|
5607
|
+
const found = await detectProject(pageUrl, claimed).catch(() => void 0);
|
|
5608
|
+
detected = automaticPart(found);
|
|
5609
|
+
if (found) {
|
|
5610
|
+
await attach(found.root, raw);
|
|
5611
|
+
return client.send({
|
|
5612
|
+
type: "project.source",
|
|
5613
|
+
source: found.source
|
|
5614
|
+
});
|
|
5615
|
+
}
|
|
4540
5616
|
return client.send({
|
|
4541
5617
|
type: "project.unknown",
|
|
4542
5618
|
pageUrl,
|
|
@@ -4549,14 +5625,42 @@ async function startDaemon(options = {}) {
|
|
|
4549
5625
|
updater.update();
|
|
4550
5626
|
return;
|
|
4551
5627
|
}
|
|
5628
|
+
if (message.type === "preferences.update") {
|
|
5629
|
+
const changes = Preferences.parse(raw.preferences);
|
|
5630
|
+
const saved = await preferences.update(changes);
|
|
5631
|
+
const update = JSON.stringify({
|
|
5632
|
+
type: "preferences",
|
|
5633
|
+
preferences: saved
|
|
5634
|
+
});
|
|
5635
|
+
for (const other of wss.clients) if (other.readyState === WebSocket$1.OPEN) other.send(update);
|
|
5636
|
+
return;
|
|
5637
|
+
}
|
|
4552
5638
|
if (message.type === "project.select" && message.root) {
|
|
4553
|
-
|
|
4554
|
-
|
|
5639
|
+
const root = message.root;
|
|
5640
|
+
const auto = detected;
|
|
5641
|
+
if (auto) await resolver.pick(pageUrl, auto.root, root);
|
|
5642
|
+
else await resolver.remember(pageUrl, root);
|
|
5643
|
+
await attach(root, {
|
|
4555
5644
|
type: "hello",
|
|
4556
5645
|
protocol: 1,
|
|
4557
5646
|
pageUrl
|
|
4558
5647
|
});
|
|
5648
|
+
const source = !auto ? { via: "picked" } : projectKey(root) === auto.root ? {
|
|
5649
|
+
via: auto.via,
|
|
5650
|
+
port: auto.port
|
|
5651
|
+
} : {
|
|
5652
|
+
via: "picked",
|
|
5653
|
+
detected: auto
|
|
5654
|
+
};
|
|
5655
|
+
return client.send({
|
|
5656
|
+
type: "project.source",
|
|
5657
|
+
source
|
|
5658
|
+
});
|
|
4559
5659
|
}
|
|
5660
|
+
if (message.type === "project.choices") return client.send({
|
|
5661
|
+
type: "project.choices",
|
|
5662
|
+
choices: await choices()
|
|
5663
|
+
});
|
|
4560
5664
|
if (!current) return client.send({
|
|
4561
5665
|
type: "error",
|
|
4562
5666
|
message: "No project selected yet"
|
|
@@ -4666,4 +5770,4 @@ function resolveOverlayPath() {
|
|
|
4666
5770
|
return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
|
|
4667
5771
|
}
|
|
4668
5772
|
//#endregion
|
|
4669
|
-
export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E,
|
|
5773
|
+
export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E, EnsembleClient as F, Bridge as I, renderPrompt as L, ProjectResolver as M, projectRoot as N, exchangePairingCredential as O, EnsembleCredentialStore as P, stripContext as R, defaultDataDir as S, CredentialStore as T, detectAgents as _, readPlan as a, savedProvider as b, runtimeDir as c, uninstallService as d, startInBackground as f, PROVIDERS as g, updateNotice as h, finishUpdate as i, loadAgentSdk as j, parsePairingInput as k, isServiceInstalled as l, isNewerThanThis as m, probeDaemon as n, enableAutostart as o, stopDaemon as p, startDaemon as r, ensureDaemon as s, DEFAULT_PORT as t, stopService as u, providerLabel as v, VERSION as w, FileThreadStore as x, saveProvider as y };
|