tencil 0.0.0-stage → 0.3.1
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/LICENSE +21 -0
- package/README.md +172 -2
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +1368 -0
- package/dist/index.d.mts +561 -0
- package/dist/index.mjs +2 -0
- package/dist/loader-BevujQ44.mjs +21 -0
- package/dist/overlay.global.js +611 -0
- package/dist/react.d.mts +17 -0
- package/dist/react.mjs +19 -0
- package/dist/server-PYBcw-eR.mjs +3205 -0
- package/dist/vite.d.mts +22 -0
- package/dist/vite.mjs +27 -0
- package/package.json +97 -3
|
@@ -0,0 +1,3205 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { access, chmod, mkdir, readFile, readlink, realpath, rename, writeFile } from "node:fs/promises";
|
|
5
|
+
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { createServer } from "node:http";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { WebSocket as WebSocket$1, WebSocketServer } from "ws";
|
|
12
|
+
//#region ../protocol/src/context.ts
|
|
13
|
+
/** A resolved source location for the element, usually from React's owner stack. */
|
|
14
|
+
const SourceLocation = z.object({
|
|
15
|
+
file: z.string(),
|
|
16
|
+
line: z.number().int().optional(),
|
|
17
|
+
column: z.number().int().optional()
|
|
18
|
+
});
|
|
19
|
+
const ComponentFrame = z.object({
|
|
20
|
+
name: z.string(),
|
|
21
|
+
source: SourceLocation.optional(),
|
|
22
|
+
/** `node_modules` package the component lives in, if it isn't app code. */
|
|
23
|
+
library: z.string().optional()
|
|
24
|
+
});
|
|
25
|
+
const Rect = z.object({
|
|
26
|
+
x: z.number(),
|
|
27
|
+
y: z.number(),
|
|
28
|
+
width: z.number(),
|
|
29
|
+
height: z.number()
|
|
30
|
+
});
|
|
31
|
+
/**
|
|
32
|
+
* Everything the overlay knows about the picked element. Captured once when
|
|
33
|
+
* the pin is placed and forwarded to the agent as context.
|
|
34
|
+
*/
|
|
35
|
+
const ElementContext = z.object({
|
|
36
|
+
tagName: z.string(),
|
|
37
|
+
selector: z.string(),
|
|
38
|
+
/** Trimmed outerHTML preview, safe to put in a prompt. */
|
|
39
|
+
html: z.string(),
|
|
40
|
+
text: z.string().optional(),
|
|
41
|
+
/** Innermost component first. */
|
|
42
|
+
components: z.array(ComponentFrame).default([]),
|
|
43
|
+
rect: Rect,
|
|
44
|
+
viewport: z.object({
|
|
45
|
+
width: z.number(),
|
|
46
|
+
height: z.number(),
|
|
47
|
+
dpr: z.number()
|
|
48
|
+
}),
|
|
49
|
+
/** Selected text inside the element at pin time, if any. */
|
|
50
|
+
selection: z.string().optional()
|
|
51
|
+
});
|
|
52
|
+
/** Where a pin sits: the element plus the click offset inside it (0..1). */
|
|
53
|
+
const Anchor = z.object({
|
|
54
|
+
selector: z.string(),
|
|
55
|
+
offsetX: z.number().min(0).max(1),
|
|
56
|
+
offsetY: z.number().min(0).max(1)
|
|
57
|
+
});
|
|
58
|
+
const ImageAttachment = z.object({
|
|
59
|
+
name: z.string(),
|
|
60
|
+
mimeType: z.enum([
|
|
61
|
+
"image/png",
|
|
62
|
+
"image/jpeg",
|
|
63
|
+
"image/webp"
|
|
64
|
+
]),
|
|
65
|
+
dataUrl: z.string().startsWith("data:image/").max(14e6)
|
|
66
|
+
});
|
|
67
|
+
const ClientMessage = z.discriminatedUnion("type", [
|
|
68
|
+
z.object({
|
|
69
|
+
type: z.literal("hello"),
|
|
70
|
+
protocol: z.literal(1),
|
|
71
|
+
pageUrl: z.string()
|
|
72
|
+
}),
|
|
73
|
+
z.object({
|
|
74
|
+
type: z.literal("thread.create"),
|
|
75
|
+
/** Client-generated id so the overlay can render the pin optimistically. */
|
|
76
|
+
id: z.string().min(1).max(64),
|
|
77
|
+
pageUrl: z.string(),
|
|
78
|
+
prompt: z.string().min(1),
|
|
79
|
+
anchor: Anchor,
|
|
80
|
+
context: ElementContext,
|
|
81
|
+
attachments: z.array(ImageAttachment).max(4).default([]),
|
|
82
|
+
/** Continue this existing provider thread instead of starting a new one. */
|
|
83
|
+
providerThreadId: z.string().optional()
|
|
84
|
+
}),
|
|
85
|
+
z.object({
|
|
86
|
+
type: z.literal("thread.open"),
|
|
87
|
+
id: z.string().min(1).max(64),
|
|
88
|
+
providerThreadId: z.string(),
|
|
89
|
+
title: z.string().optional()
|
|
90
|
+
}),
|
|
91
|
+
z.object({ type: z.literal("provider.threads") }),
|
|
92
|
+
z.object({
|
|
93
|
+
type: z.literal("project.select"),
|
|
94
|
+
root: z.string().min(1)
|
|
95
|
+
}),
|
|
96
|
+
z.object({ type: z.literal("provider.pair") }),
|
|
97
|
+
z.object({
|
|
98
|
+
type: z.literal("thread.reply"),
|
|
99
|
+
threadId: z.string(),
|
|
100
|
+
text: z.string().min(1),
|
|
101
|
+
attachments: z.array(ImageAttachment).max(4).default([])
|
|
102
|
+
}),
|
|
103
|
+
z.object({
|
|
104
|
+
type: z.literal("thread.interrupt"),
|
|
105
|
+
threadId: z.string()
|
|
106
|
+
}),
|
|
107
|
+
z.object({
|
|
108
|
+
type: z.literal("thread.resolve"),
|
|
109
|
+
threadId: z.string(),
|
|
110
|
+
resolved: z.boolean()
|
|
111
|
+
}),
|
|
112
|
+
z.object({
|
|
113
|
+
type: z.literal("thread.delete"),
|
|
114
|
+
threadId: z.string()
|
|
115
|
+
}),
|
|
116
|
+
z.object({
|
|
117
|
+
type: z.literal("settings.update"),
|
|
118
|
+
provider: z.string().min(1)
|
|
119
|
+
})
|
|
120
|
+
]);
|
|
121
|
+
z.object({
|
|
122
|
+
id: z.string(),
|
|
123
|
+
label: z.string(),
|
|
124
|
+
state: z.enum([
|
|
125
|
+
"connecting",
|
|
126
|
+
"ready",
|
|
127
|
+
"unauthorized",
|
|
128
|
+
"unavailable"
|
|
129
|
+
]),
|
|
130
|
+
detail: z.string().optional(),
|
|
131
|
+
/** Human label for where threads go, e.g. the T3 Code project name. */
|
|
132
|
+
target: z.string().optional(),
|
|
133
|
+
/** The overlay can fix `unauthorized` itself by sending `provider.pair`. */
|
|
134
|
+
canPair: z.boolean().optional()
|
|
135
|
+
});
|
|
136
|
+
/** A provider the project can send pins to. */
|
|
137
|
+
const ProviderOption = z.object({
|
|
138
|
+
id: z.string(),
|
|
139
|
+
label: z.string()
|
|
140
|
+
});
|
|
141
|
+
z.object({
|
|
142
|
+
/** Provider new pins go to; existing pins keep their own. */
|
|
143
|
+
provider: z.string(),
|
|
144
|
+
providers: z.array(ProviderOption)
|
|
145
|
+
});
|
|
146
|
+
//#endregion
|
|
147
|
+
//#region ../protocol/src/thread.ts
|
|
148
|
+
/**
|
|
149
|
+
* Provider-agnostic run state.
|
|
150
|
+
* - `starting`: thread is being created on the provider
|
|
151
|
+
* - `working`: the agent is producing a turn
|
|
152
|
+
* - `waiting`: the agent needs approval/input inside the provider UI
|
|
153
|
+
* - `idle`: last turn finished, ready for a follow-up
|
|
154
|
+
* - `error`: last turn or the thread itself failed
|
|
155
|
+
*/
|
|
156
|
+
const ThreadStatus = z.enum([
|
|
157
|
+
"starting",
|
|
158
|
+
"working",
|
|
159
|
+
"waiting",
|
|
160
|
+
"idle",
|
|
161
|
+
"error"
|
|
162
|
+
]);
|
|
163
|
+
const MessageRole = z.enum([
|
|
164
|
+
"user",
|
|
165
|
+
"assistant",
|
|
166
|
+
"system"
|
|
167
|
+
]);
|
|
168
|
+
const ThreadMessage = z.object({
|
|
169
|
+
id: z.string(),
|
|
170
|
+
role: MessageRole,
|
|
171
|
+
/** Cumulative text; replaces the previous value on every update. */
|
|
172
|
+
text: z.string(),
|
|
173
|
+
streaming: z.boolean().default(false),
|
|
174
|
+
createdAt: z.string()
|
|
175
|
+
});
|
|
176
|
+
/**
|
|
177
|
+
* A conversation Tencil tracks, backed by one provider thread. Owned and
|
|
178
|
+
* persisted by the bridge. Pinned threads sit on an element of a page;
|
|
179
|
+
* threads opened from the provider's list have no anchor and live in the dock.
|
|
180
|
+
* Several pins may continue the same provider thread.
|
|
181
|
+
*/
|
|
182
|
+
const Thread = z.object({
|
|
183
|
+
id: z.string(),
|
|
184
|
+
title: z.string(),
|
|
185
|
+
pageUrl: z.string().optional(),
|
|
186
|
+
anchor: Anchor.optional(),
|
|
187
|
+
context: ElementContext.optional(),
|
|
188
|
+
status: ThreadStatus,
|
|
189
|
+
statusDetail: z.string().optional(),
|
|
190
|
+
resolved: z.boolean().default(false),
|
|
191
|
+
messages: z.array(ThreadMessage),
|
|
192
|
+
provider: z.object({
|
|
193
|
+
id: z.string(),
|
|
194
|
+
threadId: z.string().optional(),
|
|
195
|
+
/** Deep link into the provider UI, when it has one. */
|
|
196
|
+
url: z.string().optional()
|
|
197
|
+
}),
|
|
198
|
+
createdAt: z.string(),
|
|
199
|
+
updatedAt: z.string()
|
|
200
|
+
});
|
|
201
|
+
z.object({
|
|
202
|
+
id: z.string(),
|
|
203
|
+
title: z.string(),
|
|
204
|
+
status: z.enum([
|
|
205
|
+
"working",
|
|
206
|
+
"waiting",
|
|
207
|
+
"idle",
|
|
208
|
+
"error"
|
|
209
|
+
]),
|
|
210
|
+
updatedAt: z.string(),
|
|
211
|
+
url: z.string().optional(),
|
|
212
|
+
branch: z.string().optional(),
|
|
213
|
+
pullRequest: z.object({
|
|
214
|
+
number: z.number(),
|
|
215
|
+
url: z.string()
|
|
216
|
+
}).optional(),
|
|
217
|
+
/** Work still running after the turn settled (subagents, watch loops). */
|
|
218
|
+
background: z.enum(["working", "monitoring"]).optional(),
|
|
219
|
+
/** Agent driver, e.g. `codex` or `claudeAgent`, for the provider icon. */
|
|
220
|
+
agent: z.string().optional()
|
|
221
|
+
});
|
|
222
|
+
z.object({
|
|
223
|
+
name: z.string(),
|
|
224
|
+
/** Absolute URL of the project's favicon, if it has one. */
|
|
225
|
+
iconUrl: z.string().optional(),
|
|
226
|
+
emoji: z.string().optional()
|
|
227
|
+
});
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/daemon/prompt.ts
|
|
230
|
+
const CONTEXT_OPEN = "<tencil-context>";
|
|
231
|
+
const CONTEXT_CLOSE = "</tencil-context>";
|
|
232
|
+
/**
|
|
233
|
+
* Renders the text sent to the agent: the user's words first, then a fenced
|
|
234
|
+
* block of element context. The block is stripped again before messages are
|
|
235
|
+
* shown in the overlay (`stripContext`).
|
|
236
|
+
*/
|
|
237
|
+
function renderPrompt(input) {
|
|
238
|
+
const { context } = input;
|
|
239
|
+
const lines = [
|
|
240
|
+
"The user pinned this comment on an element of their running app (via Tencil). Use the context below to locate the code, then make the change in this workspace.",
|
|
241
|
+
"",
|
|
242
|
+
`- Page: ${input.pageUrl}`,
|
|
243
|
+
`- Element: \`${oneLine(context.html)}\``
|
|
244
|
+
];
|
|
245
|
+
const [component, ...owners] = context.components;
|
|
246
|
+
if (component) {
|
|
247
|
+
const chain = [component, ...owners.slice(0, 4)].map(formatFrame).join(" ← ");
|
|
248
|
+
lines.push(`- Component: ${chain}`);
|
|
249
|
+
}
|
|
250
|
+
lines.push(`- Selector: \`${context.selector}\``);
|
|
251
|
+
if (context.text) lines.push(`- Visible text: "${truncate(oneLine(context.text), 200)}"`);
|
|
252
|
+
if (context.selection) lines.push(`- Selected text: "${truncate(oneLine(context.selection), 300)}"`);
|
|
253
|
+
const { rect, viewport } = context;
|
|
254
|
+
lines.push(`- Layout: ${Math.round(rect.width)}×${Math.round(rect.height)} at (${Math.round(rect.x)}, ${Math.round(rect.y)}) in a ${viewport.width}×${viewport.height} viewport @${viewport.dpr}x`);
|
|
255
|
+
if (input.hasScreenshot) lines.push("- A screenshot of the element is attached.");
|
|
256
|
+
return `${input.prompt.trim()}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
|
|
257
|
+
}
|
|
258
|
+
function stripContext(text) {
|
|
259
|
+
const index = text.indexOf(CONTEXT_OPEN);
|
|
260
|
+
return index === -1 ? text : text.slice(0, index).trimEnd();
|
|
261
|
+
}
|
|
262
|
+
function titleFor(prompt, context) {
|
|
263
|
+
const firstLine = prompt.trim().split("\n", 1)[0] ?? "";
|
|
264
|
+
return truncate(`${context.components[0]?.name ?? `<${context.tagName}>`}: ${firstLine}`, 80);
|
|
265
|
+
}
|
|
266
|
+
function formatFrame(frame) {
|
|
267
|
+
if (frame.library) return `${frame.name} (${frame.library})`;
|
|
268
|
+
if (!frame.source) return frame.name;
|
|
269
|
+
const position = [frame.source.line, frame.source.column].filter((n) => n != null).join(":");
|
|
270
|
+
return `${frame.name} (${frame.source.file}${position ? `:${position}` : ""})`;
|
|
271
|
+
}
|
|
272
|
+
function oneLine(text) {
|
|
273
|
+
return text.replace(/\s+/g, " ").trim();
|
|
274
|
+
}
|
|
275
|
+
function truncate(text, max) {
|
|
276
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
277
|
+
}
|
|
278
|
+
//#endregion
|
|
279
|
+
//#region src/daemon/bridge.ts
|
|
280
|
+
/** Local echo ids, replaced once the provider reports the real user message. */
|
|
281
|
+
const LOCAL_PREFIX = "local:";
|
|
282
|
+
const BROADCAST_THROTTLE_MS = 80;
|
|
283
|
+
/**
|
|
284
|
+
* Owns pins and fans provider updates out to every connected overlay. One
|
|
285
|
+
* bridge serves one project; any number of tabs may be connected.
|
|
286
|
+
*/
|
|
287
|
+
var Bridge = class {
|
|
288
|
+
#options;
|
|
289
|
+
#clients = /* @__PURE__ */ new Set();
|
|
290
|
+
/** One provider subscription per provider thread, shared by every pin bound to it. */
|
|
291
|
+
#watches = /* @__PURE__ */ new Map();
|
|
292
|
+
#pendingBroadcast = /* @__PURE__ */ new Map();
|
|
293
|
+
#offInfo = () => {};
|
|
294
|
+
#offDefault;
|
|
295
|
+
constructor(options) {
|
|
296
|
+
this.#options = options;
|
|
297
|
+
this.#followDefault();
|
|
298
|
+
this.#offDefault = options.providers.onDefaultChange(() => {
|
|
299
|
+
this.#followDefault();
|
|
300
|
+
this.#broadcast({
|
|
301
|
+
type: "settings",
|
|
302
|
+
settings: this.#settings()
|
|
303
|
+
});
|
|
304
|
+
this.#broadcast({
|
|
305
|
+
type: "provider.status",
|
|
306
|
+
provider: this.#provider().info()
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
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);
|
|
310
|
+
}
|
|
311
|
+
connect(client) {
|
|
312
|
+
this.#clients.add(client);
|
|
313
|
+
return () => this.#clients.delete(client);
|
|
314
|
+
}
|
|
315
|
+
async handle(client, raw) {
|
|
316
|
+
const parsed = ClientMessage.safeParse(raw);
|
|
317
|
+
if (!parsed.success) {
|
|
318
|
+
client.send({
|
|
319
|
+
type: "error",
|
|
320
|
+
message: `Invalid message: ${parsed.error.issues[0]?.message}`
|
|
321
|
+
});
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const message = parsed.data;
|
|
325
|
+
try {
|
|
326
|
+
switch (message.type) {
|
|
327
|
+
case "hello":
|
|
328
|
+
client.send({
|
|
329
|
+
type: "ready",
|
|
330
|
+
protocol: 1,
|
|
331
|
+
version: this.#options.version,
|
|
332
|
+
project: this.#options.project,
|
|
333
|
+
provider: this.#provider().info(),
|
|
334
|
+
settings: this.#settings(),
|
|
335
|
+
threads: this.#options.store.list()
|
|
336
|
+
});
|
|
337
|
+
return;
|
|
338
|
+
case "thread.create":
|
|
339
|
+
await (message.providerThreadId ? this.#continue(message) : this.#create(message));
|
|
340
|
+
return;
|
|
341
|
+
case "thread.open":
|
|
342
|
+
this.#open(message);
|
|
343
|
+
return;
|
|
344
|
+
case "provider.pair":
|
|
345
|
+
await this.#provider().pair?.();
|
|
346
|
+
return;
|
|
347
|
+
case "provider.threads":
|
|
348
|
+
client.send({
|
|
349
|
+
type: "provider.threads",
|
|
350
|
+
...await this.#provider().listThreads()
|
|
351
|
+
});
|
|
352
|
+
return;
|
|
353
|
+
case "settings.update":
|
|
354
|
+
await this.#options.providers.setDefault(message.provider);
|
|
355
|
+
return;
|
|
356
|
+
case "thread.reply":
|
|
357
|
+
await this.#reply(message);
|
|
358
|
+
return;
|
|
359
|
+
case "thread.interrupt": {
|
|
360
|
+
const thread = this.#require(message.threadId);
|
|
361
|
+
if (thread.provider.threadId) await this.#providerOf(thread).interrupt(thread.provider.threadId);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
case "thread.resolve":
|
|
365
|
+
this.#update(message.threadId, (thread) => ({
|
|
366
|
+
...thread,
|
|
367
|
+
resolved: message.resolved
|
|
368
|
+
}));
|
|
369
|
+
return;
|
|
370
|
+
case "thread.delete": {
|
|
371
|
+
const provider = this.#options.store.get(message.threadId)?.provider;
|
|
372
|
+
if (this.#options.store.delete(message.threadId)) this.#broadcast({
|
|
373
|
+
type: "thread.removed",
|
|
374
|
+
threadId: message.threadId
|
|
375
|
+
});
|
|
376
|
+
if (provider?.threadId) this.#release(provider.id, provider.threadId);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
} catch (error) {
|
|
381
|
+
const threadId = "threadId" in message ? message.threadId : void 0;
|
|
382
|
+
client.send({
|
|
383
|
+
type: "error",
|
|
384
|
+
message: error instanceof Error ? error.message : String(error),
|
|
385
|
+
...threadId ? { threadId } : {}
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
async dispose() {
|
|
390
|
+
this.#offInfo();
|
|
391
|
+
this.#offDefault();
|
|
392
|
+
for (const unwatch of this.#watches.values()) unwatch();
|
|
393
|
+
for (const timer of this.#pendingBroadcast.values()) clearTimeout(timer);
|
|
394
|
+
await this.#options.store.flush();
|
|
395
|
+
}
|
|
396
|
+
async #create(message) {
|
|
397
|
+
const { store } = this.#options;
|
|
398
|
+
const provider = this.#provider();
|
|
399
|
+
if (store.get(message.id)) throw new Error(`Thread ${message.id} already exists`);
|
|
400
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
401
|
+
const thread = {
|
|
402
|
+
id: message.id,
|
|
403
|
+
title: titleFor(message.prompt, message.context),
|
|
404
|
+
pageUrl: message.pageUrl,
|
|
405
|
+
anchor: message.anchor,
|
|
406
|
+
context: message.context,
|
|
407
|
+
status: "starting",
|
|
408
|
+
resolved: false,
|
|
409
|
+
messages: [localMessage(message.prompt, now)],
|
|
410
|
+
provider: { id: provider.id },
|
|
411
|
+
createdAt: now,
|
|
412
|
+
updatedAt: now
|
|
413
|
+
};
|
|
414
|
+
store.upsert(thread);
|
|
415
|
+
this.#broadcastThread(thread, true);
|
|
416
|
+
try {
|
|
417
|
+
const created = await provider.createThread({
|
|
418
|
+
title: thread.title,
|
|
419
|
+
text: renderPrompt({
|
|
420
|
+
prompt: message.prompt,
|
|
421
|
+
pageUrl: message.pageUrl,
|
|
422
|
+
context: message.context,
|
|
423
|
+
hasScreenshot: message.attachments.length > 0
|
|
424
|
+
}),
|
|
425
|
+
attachments: message.attachments
|
|
426
|
+
});
|
|
427
|
+
this.#update(thread.id, (current) => ({
|
|
428
|
+
...current,
|
|
429
|
+
status: "working",
|
|
430
|
+
provider: {
|
|
431
|
+
id: provider.id,
|
|
432
|
+
threadId: created.providerThreadId,
|
|
433
|
+
url: created.url
|
|
434
|
+
}
|
|
435
|
+
}));
|
|
436
|
+
this.#watch(provider.id, created.providerThreadId);
|
|
437
|
+
this.#options.log?.(`Pin "${thread.title}" → ${provider.label}`);
|
|
438
|
+
} catch (error) {
|
|
439
|
+
this.#update(thread.id, (current) => ({
|
|
440
|
+
...current,
|
|
441
|
+
status: "error",
|
|
442
|
+
statusDetail: error instanceof Error ? error.message : String(error)
|
|
443
|
+
}));
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
/** Pin an element onto an existing provider thread: the prompt becomes its next message. */
|
|
447
|
+
async #continue(message) {
|
|
448
|
+
const { store } = this.#options;
|
|
449
|
+
const provider = this.#provider();
|
|
450
|
+
const providerThreadId = message.providerThreadId;
|
|
451
|
+
if (store.get(message.id)) throw new Error(`Thread ${message.id} already exists`);
|
|
452
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
453
|
+
const sibling = this.#pinsFor(provider.id, providerThreadId)[0];
|
|
454
|
+
const thread = {
|
|
455
|
+
id: message.id,
|
|
456
|
+
title: titleFor(message.prompt, message.context),
|
|
457
|
+
pageUrl: message.pageUrl,
|
|
458
|
+
anchor: message.anchor,
|
|
459
|
+
context: message.context,
|
|
460
|
+
status: "working",
|
|
461
|
+
resolved: false,
|
|
462
|
+
messages: [...sibling?.messages ?? [], localMessage(message.prompt, now)],
|
|
463
|
+
provider: {
|
|
464
|
+
id: provider.id,
|
|
465
|
+
threadId: providerThreadId,
|
|
466
|
+
url: provider.threadUrl(providerThreadId)
|
|
467
|
+
},
|
|
468
|
+
createdAt: now,
|
|
469
|
+
updatedAt: now
|
|
470
|
+
};
|
|
471
|
+
store.upsert(thread);
|
|
472
|
+
this.#broadcastThread(thread, true);
|
|
473
|
+
this.#watch(provider.id, providerThreadId, true);
|
|
474
|
+
try {
|
|
475
|
+
await provider.sendMessage({
|
|
476
|
+
providerThreadId,
|
|
477
|
+
text: renderPrompt({
|
|
478
|
+
prompt: message.prompt,
|
|
479
|
+
pageUrl: message.pageUrl,
|
|
480
|
+
context: message.context,
|
|
481
|
+
hasScreenshot: message.attachments.length > 0
|
|
482
|
+
}),
|
|
483
|
+
attachments: message.attachments
|
|
484
|
+
});
|
|
485
|
+
this.#options.log?.(`Pin "${thread.title}" → existing ${provider.label} thread`);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
this.#update(thread.id, (current) => ({
|
|
488
|
+
...current,
|
|
489
|
+
status: "error",
|
|
490
|
+
statusDetail: error instanceof Error ? error.message : String(error)
|
|
491
|
+
}));
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/** Track an existing provider thread without an element, e.g. to continue it from the dock. */
|
|
495
|
+
#open(message) {
|
|
496
|
+
const { store } = this.#options;
|
|
497
|
+
const provider = this.#provider();
|
|
498
|
+
const pins = this.#pinsFor(provider.id, message.providerThreadId);
|
|
499
|
+
const existing = pins.find((thread) => !thread.anchor);
|
|
500
|
+
if (existing) {
|
|
501
|
+
this.#broadcastThread(existing, true);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const sibling = pins[0];
|
|
505
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
506
|
+
const thread = {
|
|
507
|
+
id: message.id,
|
|
508
|
+
title: message.title ?? sibling?.title ?? "Thread",
|
|
509
|
+
status: sibling?.status ?? "idle",
|
|
510
|
+
resolved: false,
|
|
511
|
+
messages: sibling?.messages ?? [],
|
|
512
|
+
provider: {
|
|
513
|
+
id: provider.id,
|
|
514
|
+
threadId: message.providerThreadId,
|
|
515
|
+
url: provider.threadUrl(message.providerThreadId)
|
|
516
|
+
},
|
|
517
|
+
createdAt: now,
|
|
518
|
+
updatedAt: now
|
|
519
|
+
};
|
|
520
|
+
store.upsert(thread);
|
|
521
|
+
this.#broadcastThread(thread, true);
|
|
522
|
+
this.#watch(provider.id, message.providerThreadId, true);
|
|
523
|
+
}
|
|
524
|
+
async #reply(message) {
|
|
525
|
+
const thread = this.#require(message.threadId);
|
|
526
|
+
if (!thread.provider.threadId) throw new Error("This pin has no agent thread yet");
|
|
527
|
+
this.#update(thread.id, (current) => ({
|
|
528
|
+
...current,
|
|
529
|
+
resolved: false,
|
|
530
|
+
status: "working",
|
|
531
|
+
statusDetail: void 0,
|
|
532
|
+
messages: [...current.messages, localMessage(message.text, (/* @__PURE__ */ new Date()).toISOString())]
|
|
533
|
+
}));
|
|
534
|
+
await this.#providerOf(thread).sendMessage({
|
|
535
|
+
providerThreadId: thread.provider.threadId,
|
|
536
|
+
text: message.text,
|
|
537
|
+
attachments: message.attachments
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Subscribe once per provider thread and fan updates out to every bound pin.
|
|
542
|
+
* `replay` re-subscribes an existing watch so a newly bound pin receives the
|
|
543
|
+
* provider's snapshot too.
|
|
544
|
+
*/
|
|
545
|
+
#watch(providerId, providerThreadId, replay = false) {
|
|
546
|
+
const key = watchKey(providerId, providerThreadId);
|
|
547
|
+
if (this.#watches.has(key) && !replay) return;
|
|
548
|
+
this.#watches.get(key)?.();
|
|
549
|
+
const provider = this.#options.providers.get(providerId);
|
|
550
|
+
const each = (change) => {
|
|
551
|
+
for (const thread of this.#pinsFor(providerId, providerThreadId)) this.#update(thread.id, change);
|
|
552
|
+
};
|
|
553
|
+
const unwatch = provider.watch(providerThreadId, {
|
|
554
|
+
message: (message) => each((thread) => mergeMessage(thread, message)),
|
|
555
|
+
status: (status, statusDetail) => each((thread) => ({
|
|
556
|
+
...thread,
|
|
557
|
+
status,
|
|
558
|
+
statusDetail
|
|
559
|
+
})),
|
|
560
|
+
gone: () => each((thread) => ({
|
|
561
|
+
...thread,
|
|
562
|
+
status: "error",
|
|
563
|
+
statusDetail: `Thread no longer exists in ${provider.label}`
|
|
564
|
+
}))
|
|
565
|
+
});
|
|
566
|
+
this.#watches.set(key, unwatch);
|
|
567
|
+
}
|
|
568
|
+
#release(providerId, providerThreadId) {
|
|
569
|
+
if (this.#pinsFor(providerId, providerThreadId).length > 0) return;
|
|
570
|
+
const key = watchKey(providerId, providerThreadId);
|
|
571
|
+
this.#watches.get(key)?.();
|
|
572
|
+
this.#watches.delete(key);
|
|
573
|
+
}
|
|
574
|
+
#pinsFor(providerId, providerThreadId) {
|
|
575
|
+
return this.#options.store.list().filter((thread) => thread.provider.id === providerId && thread.provider.threadId === providerThreadId);
|
|
576
|
+
}
|
|
577
|
+
/** The provider new pins go to. */
|
|
578
|
+
#provider() {
|
|
579
|
+
return this.#options.providers.default();
|
|
580
|
+
}
|
|
581
|
+
/** The provider a pin was made with; switching the default doesn't move old pins. */
|
|
582
|
+
#providerOf(thread) {
|
|
583
|
+
if (!this.#options.providers.has(thread.provider.id)) throw new Error(`This pin's agent (${thread.provider.id}) isn't available`);
|
|
584
|
+
return this.#options.providers.get(thread.provider.id);
|
|
585
|
+
}
|
|
586
|
+
/** Report the default provider's status, and follow it when the project switches. */
|
|
587
|
+
#followDefault() {
|
|
588
|
+
this.#offInfo();
|
|
589
|
+
this.#offInfo = this.#provider().onInfoChange((provider) => this.#broadcast({
|
|
590
|
+
type: "provider.status",
|
|
591
|
+
provider
|
|
592
|
+
}));
|
|
593
|
+
}
|
|
594
|
+
#settings() {
|
|
595
|
+
const { providers } = this.#options;
|
|
596
|
+
return {
|
|
597
|
+
provider: providers.defaultId,
|
|
598
|
+
providers: providers.choices
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
#require(threadId) {
|
|
602
|
+
const thread = this.#options.store.get(threadId);
|
|
603
|
+
if (!thread) throw new Error(`Unknown thread ${threadId}`);
|
|
604
|
+
return thread;
|
|
605
|
+
}
|
|
606
|
+
#update(threadId, change) {
|
|
607
|
+
const current = this.#options.store.get(threadId);
|
|
608
|
+
if (!current) return;
|
|
609
|
+
const next = {
|
|
610
|
+
...change(current),
|
|
611
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
612
|
+
};
|
|
613
|
+
this.#options.store.upsert(next);
|
|
614
|
+
this.#broadcastThread(next);
|
|
615
|
+
}
|
|
616
|
+
/** Streaming produces many updates per second; coalesce per thread. */
|
|
617
|
+
#broadcastThread(thread, immediate = false) {
|
|
618
|
+
const send = () => {
|
|
619
|
+
this.#pendingBroadcast.delete(thread.id);
|
|
620
|
+
const latest = this.#options.store.get(thread.id);
|
|
621
|
+
if (latest) this.#broadcast({
|
|
622
|
+
type: "thread.upsert",
|
|
623
|
+
thread: latest
|
|
624
|
+
});
|
|
625
|
+
};
|
|
626
|
+
if (immediate) {
|
|
627
|
+
clearTimeout(this.#pendingBroadcast.get(thread.id));
|
|
628
|
+
send();
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
if (this.#pendingBroadcast.has(thread.id)) return;
|
|
632
|
+
this.#pendingBroadcast.set(thread.id, setTimeout(send, BROADCAST_THROTTLE_MS));
|
|
633
|
+
}
|
|
634
|
+
#broadcast(message) {
|
|
635
|
+
for (const client of this.#clients) client.send(message);
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
function watchKey(providerId, providerThreadId) {
|
|
639
|
+
return `${providerId}:${providerThreadId}`;
|
|
640
|
+
}
|
|
641
|
+
function localMessage(text, createdAt) {
|
|
642
|
+
return {
|
|
643
|
+
id: `${LOCAL_PREFIX}${crypto.randomUUID()}`,
|
|
644
|
+
role: "user",
|
|
645
|
+
text,
|
|
646
|
+
streaming: false,
|
|
647
|
+
createdAt
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
function mergeMessage(thread, incoming) {
|
|
651
|
+
const message = {
|
|
652
|
+
...incoming,
|
|
653
|
+
text: incoming.role === "user" ? stripContext(incoming.text) : incoming.text
|
|
654
|
+
};
|
|
655
|
+
let messages = thread.messages;
|
|
656
|
+
if (message.role === "user") {
|
|
657
|
+
const echo = messages.findIndex((m) => m.id.startsWith(LOCAL_PREFIX) && m.text.trim() === message.text.trim());
|
|
658
|
+
if (echo !== -1) messages = messages.filter((_, index) => index !== echo);
|
|
659
|
+
}
|
|
660
|
+
const index = messages.findIndex((m) => m.id === message.id);
|
|
661
|
+
if (index === -1) messages = [...messages, message].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || Number(a.id.startsWith(LOCAL_PREFIX)) - Number(b.id.startsWith(LOCAL_PREFIX)));
|
|
662
|
+
else messages = messages.map((m, i) => i === index ? message : m);
|
|
663
|
+
return {
|
|
664
|
+
...thread,
|
|
665
|
+
messages
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
//#endregion
|
|
669
|
+
//#region src/daemon/project-resolver.ts
|
|
670
|
+
const run$1 = promisify(execFile);
|
|
671
|
+
const defaultExec = async (command, args) => (await run$1(command, args, {
|
|
672
|
+
timeout: 3e3,
|
|
673
|
+
windowsHide: true
|
|
674
|
+
})).stdout;
|
|
675
|
+
/**
|
|
676
|
+
* Works out which project folder a page belongs to:
|
|
677
|
+
* 1. what the user picked for this address before,
|
|
678
|
+
* 2. the dev server's working directory, found from the port it listens on.
|
|
679
|
+
* Returns undefined when neither works; the overlay then asks.
|
|
680
|
+
*/
|
|
681
|
+
var ProjectResolver = class {
|
|
682
|
+
#memory;
|
|
683
|
+
#exec;
|
|
684
|
+
#platform;
|
|
685
|
+
constructor(options) {
|
|
686
|
+
this.#memory = new OriginMemory(join(options.dataDir, "origins.json"));
|
|
687
|
+
this.#exec = options.exec ?? defaultExec;
|
|
688
|
+
this.#platform = options.platform ?? process.platform;
|
|
689
|
+
}
|
|
690
|
+
async resolve(pageUrl) {
|
|
691
|
+
const origin = safeOrigin(pageUrl);
|
|
692
|
+
if (!origin) return void 0;
|
|
693
|
+
const remembered = await this.#memory.get(origin);
|
|
694
|
+
if (remembered && existsSync(remembered)) return remembered;
|
|
695
|
+
const port = portOf(origin);
|
|
696
|
+
if (!port) return void 0;
|
|
697
|
+
const folder = await this.folderForPort(port).catch(() => void 0);
|
|
698
|
+
return folder ? projectRoot(folder) : void 0;
|
|
699
|
+
}
|
|
700
|
+
/** Remember the user's choice for an address (from the overlay's project picker). */
|
|
701
|
+
remember(pageUrl, root) {
|
|
702
|
+
const origin = safeOrigin(pageUrl);
|
|
703
|
+
return origin ? this.#memory.set(origin, resolve(root)) : Promise.resolve();
|
|
704
|
+
}
|
|
705
|
+
/** Folder of the process listening on `port`: its working directory, or its script's package. */
|
|
706
|
+
async folderForPort(port) {
|
|
707
|
+
for (const pid of await this.#listeners(port)) {
|
|
708
|
+
const cwd = await this.#cwd(pid).catch(() => void 0);
|
|
709
|
+
if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return cwd;
|
|
710
|
+
const fromCommand = projectFromCommandLine(await this.#commandLine(pid).catch(() => ""));
|
|
711
|
+
if (fromCommand) return fromCommand;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
async #listeners(port) {
|
|
715
|
+
if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", [
|
|
716
|
+
"-ano",
|
|
717
|
+
"-p",
|
|
718
|
+
"TCP"
|
|
719
|
+
]), port);
|
|
720
|
+
try {
|
|
721
|
+
return parsePids(await this.#exec("lsof", [
|
|
722
|
+
"-nP",
|
|
723
|
+
`-iTCP:${port}`,
|
|
724
|
+
"-sTCP:LISTEN",
|
|
725
|
+
"-t"
|
|
726
|
+
]));
|
|
727
|
+
} catch (error) {
|
|
728
|
+
if (this.#platform !== "linux") throw error;
|
|
729
|
+
return parseSs(await this.#exec("ss", ["-Hltnp", `sport = :${port}`]));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
async #cwd(pid) {
|
|
733
|
+
if (this.#platform === "linux") return readlink(`/proc/${pid}/cwd`);
|
|
734
|
+
if (this.#platform === "win32") return void 0;
|
|
735
|
+
return parseLsofCwd(await this.#exec("lsof", [
|
|
736
|
+
"-a",
|
|
737
|
+
"-p",
|
|
738
|
+
String(pid),
|
|
739
|
+
"-d",
|
|
740
|
+
"cwd",
|
|
741
|
+
"-Fn"
|
|
742
|
+
]));
|
|
743
|
+
}
|
|
744
|
+
async #commandLine(pid) {
|
|
745
|
+
if (this.#platform === "win32") return this.#exec("powershell", [
|
|
746
|
+
"-NoProfile",
|
|
747
|
+
"-Command",
|
|
748
|
+
`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`
|
|
749
|
+
]);
|
|
750
|
+
return this.#exec("ps", [
|
|
751
|
+
"-o",
|
|
752
|
+
"command=",
|
|
753
|
+
"-p",
|
|
754
|
+
String(pid)
|
|
755
|
+
]);
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
/** Closest folder with a package.json at or above `folder`, or `folder` itself. */
|
|
759
|
+
function projectRoot(folder) {
|
|
760
|
+
let dir = resolve(folder);
|
|
761
|
+
while (true) {
|
|
762
|
+
if (existsSync(join(dir, "package.json"))) return dir;
|
|
763
|
+
const parent = dirname(dir);
|
|
764
|
+
if (parent === dir) return resolve(folder);
|
|
765
|
+
dir = parent;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
function parsePids(output) {
|
|
769
|
+
return [...new Set(output.split(/\s+/).filter(Boolean).map(Number).filter(Number.isInteger))];
|
|
770
|
+
}
|
|
771
|
+
/** `lsof -Fn` prints fields one per line; the path is on the line starting with `n`. */
|
|
772
|
+
function parseLsofCwd(output) {
|
|
773
|
+
return output.split("\n").find((line) => line.startsWith("n"))?.slice(1).trim();
|
|
774
|
+
}
|
|
775
|
+
/** PIDs from `ss -Hltnp`: `users:(("node",pid=4242,fd=23))`. */
|
|
776
|
+
function parseSs(output) {
|
|
777
|
+
return [...new Set([...output.matchAll(/pid=(\d+)/g)].map((match) => Number(match[1])))];
|
|
778
|
+
}
|
|
779
|
+
/** PIDs in LISTENING state on `port` from `netstat -ano`. */
|
|
780
|
+
function parseNetstat(output, port) {
|
|
781
|
+
const pids = output.split(/\r?\n/).map((line) => line.trim().split(/\s+/)).filter(([proto, local, , state]) => proto === "TCP" && state === "LISTENING" && local?.endsWith(`:${port}`)).map((columns) => Number(columns.at(-1)));
|
|
782
|
+
return [...new Set(pids.filter(Number.isInteger))];
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Dev servers are started from a project's node_modules
|
|
786
|
+
* (`…/eyes/apps/frontend/node_modules/next/dist/bin/next dev`): the part
|
|
787
|
+
* before `node_modules` is the project.
|
|
788
|
+
*/
|
|
789
|
+
function projectFromCommandLine(commandLine) {
|
|
790
|
+
return commandLine.match(/(?:^|[\s"'])((?:[A-Za-z]:)?[\\/][^\s"']*?)[\\/]node_modules[\\/]/)?.[1];
|
|
791
|
+
}
|
|
792
|
+
function safeOrigin(pageUrl) {
|
|
793
|
+
try {
|
|
794
|
+
return new URL(pageUrl).origin;
|
|
795
|
+
} catch {
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
function portOf(origin) {
|
|
800
|
+
const url = new URL(origin);
|
|
801
|
+
if (url.port) return Number(url.port);
|
|
802
|
+
return url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : void 0;
|
|
803
|
+
}
|
|
804
|
+
/** Remembered address → project choices, e.g. for dev servers in containers. */
|
|
805
|
+
var OriginMemory = class {
|
|
806
|
+
path;
|
|
807
|
+
constructor(path) {
|
|
808
|
+
this.path = path;
|
|
809
|
+
}
|
|
810
|
+
async get(origin) {
|
|
811
|
+
return (await this.#read())[origin];
|
|
812
|
+
}
|
|
813
|
+
async set(origin, root) {
|
|
814
|
+
const all = await this.#read();
|
|
815
|
+
all[origin] = root;
|
|
816
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
817
|
+
await writeFile(this.path, `${JSON.stringify(all, null, 2)}\n`);
|
|
818
|
+
}
|
|
819
|
+
async #read() {
|
|
820
|
+
try {
|
|
821
|
+
return JSON.parse(await readFile(this.path, "utf8"));
|
|
822
|
+
} catch {
|
|
823
|
+
return {};
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
//#endregion
|
|
828
|
+
//#region ../provider-claude-code/src/input-queue.ts
|
|
829
|
+
/** An async iterable fed by `push`; the Agent SDK reads a session's user messages from it. */
|
|
830
|
+
var InputQueue = class {
|
|
831
|
+
#items = [];
|
|
832
|
+
#waiting;
|
|
833
|
+
#closed = false;
|
|
834
|
+
push(item) {
|
|
835
|
+
if (this.#closed) throw new Error("Input is closed");
|
|
836
|
+
const waiting = this.#waiting;
|
|
837
|
+
if (waiting) {
|
|
838
|
+
this.#waiting = void 0;
|
|
839
|
+
waiting({
|
|
840
|
+
value: item,
|
|
841
|
+
done: false
|
|
842
|
+
});
|
|
843
|
+
} else this.#items.push(item);
|
|
844
|
+
}
|
|
845
|
+
close() {
|
|
846
|
+
this.#closed = true;
|
|
847
|
+
this.#waiting?.({
|
|
848
|
+
value: void 0,
|
|
849
|
+
done: true
|
|
850
|
+
});
|
|
851
|
+
this.#waiting = void 0;
|
|
852
|
+
}
|
|
853
|
+
[Symbol.asyncIterator]() {
|
|
854
|
+
return { next: () => {
|
|
855
|
+
const item = this.#items.shift();
|
|
856
|
+
if (item !== void 0) return Promise.resolve({
|
|
857
|
+
value: item,
|
|
858
|
+
done: false
|
|
859
|
+
});
|
|
860
|
+
if (this.#closed) return Promise.resolve({
|
|
861
|
+
value: void 0,
|
|
862
|
+
done: true
|
|
863
|
+
});
|
|
864
|
+
return new Promise((resolve) => {
|
|
865
|
+
this.#waiting = resolve;
|
|
866
|
+
});
|
|
867
|
+
} };
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
//#endregion
|
|
871
|
+
//#region ../provider-claude-code/src/load-sdk.ts
|
|
872
|
+
const PACKAGE = "@anthropic-ai/claude-agent-sdk";
|
|
873
|
+
/** The range this provider is written against; installs stay inside it. */
|
|
874
|
+
const SDK_RANGE = "^0.3.293";
|
|
875
|
+
const run = promisify(execFile);
|
|
876
|
+
/**
|
|
877
|
+
* The Agent SDK ships Claude Code itself (a ~250 MB binary), so `tencil`
|
|
878
|
+
* doesn't depend on it. Use a copy next to Tencil when there is one,
|
|
879
|
+
* otherwise install it once into `installDir`.
|
|
880
|
+
*/
|
|
881
|
+
async function loadAgentSdk(options) {
|
|
882
|
+
try {
|
|
883
|
+
return await import(PACKAGE);
|
|
884
|
+
} catch {}
|
|
885
|
+
const entry = join(options.installDir, "node_modules", ...PACKAGE.split("/"), "sdk.mjs");
|
|
886
|
+
if (!existsSync(entry)) {
|
|
887
|
+
options.onInstall?.();
|
|
888
|
+
await installAgentSdk(options.installDir);
|
|
889
|
+
}
|
|
890
|
+
return import(pathToFileURL(entry).href);
|
|
891
|
+
}
|
|
892
|
+
async function installAgentSdk(installDir) {
|
|
893
|
+
await mkdir(installDir, { recursive: true });
|
|
894
|
+
const manifest = join(installDir, "package.json");
|
|
895
|
+
if (!existsSync(manifest)) await writeFile(manifest, `${JSON.stringify({ private: true }, null, 4)}\n`);
|
|
896
|
+
try {
|
|
897
|
+
await run("npm", [
|
|
898
|
+
"install",
|
|
899
|
+
`${PACKAGE}@${SDK_RANGE}`,
|
|
900
|
+
"--no-audit",
|
|
901
|
+
"--no-fund",
|
|
902
|
+
"--loglevel=error"
|
|
903
|
+
], {
|
|
904
|
+
cwd: installDir,
|
|
905
|
+
shell: process.platform === "win32",
|
|
906
|
+
timeout: 6e5,
|
|
907
|
+
env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("npm_")))
|
|
908
|
+
});
|
|
909
|
+
} catch (error) {
|
|
910
|
+
const stderr = error.stderr?.trim();
|
|
911
|
+
throw new Error(`Couldn't install Claude Code support (${PACKAGE})${stderr ? `: ${stderr.split("\n").at(-1)}` : ""}`);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
//#endregion
|
|
915
|
+
//#region ../provider-claude-code/src/transcript.ts
|
|
916
|
+
/**
|
|
917
|
+
* Folds the live SDK message stream of one session into cumulative
|
|
918
|
+
* `ProviderMessage`s. Assistant messages are keyed by their API message id,
|
|
919
|
+
* the same id the transcript on disk carries, so a replay lines up with them.
|
|
920
|
+
* Subagent output and tool results stay out: the overlay shows the conversation.
|
|
921
|
+
*/
|
|
922
|
+
var TurnTracker = class {
|
|
923
|
+
#drafts = /* @__PURE__ */ new Map();
|
|
924
|
+
#current;
|
|
925
|
+
#status = { status: "idle" };
|
|
926
|
+
status() {
|
|
927
|
+
return this.#status;
|
|
928
|
+
}
|
|
929
|
+
setStatus(status) {
|
|
930
|
+
this.#status = status;
|
|
931
|
+
}
|
|
932
|
+
apply(message, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
933
|
+
const update = { messages: [] };
|
|
934
|
+
switch (message.type) {
|
|
935
|
+
case "stream_event": {
|
|
936
|
+
if (message.parent_tool_use_id) break;
|
|
937
|
+
const { event } = message;
|
|
938
|
+
if (event.type === "message_start") this.#begin(event.message.id, now, update);
|
|
939
|
+
else if (event.type === "content_block_start") {
|
|
940
|
+
const draft = this.#currentDraft();
|
|
941
|
+
if (draft && event.content_block.type === "text") draft.partial = event.content_block.text;
|
|
942
|
+
} else if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
|
|
943
|
+
const draft = this.#currentDraft();
|
|
944
|
+
if (draft) {
|
|
945
|
+
draft.partial += event.delta.text;
|
|
946
|
+
update.messages.push(toMessage(draft));
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
break;
|
|
950
|
+
}
|
|
951
|
+
case "assistant": {
|
|
952
|
+
if (message.parent_tool_use_id) break;
|
|
953
|
+
const draft = this.#begin(message.message.id, now, update);
|
|
954
|
+
for (const block of message.message.content) {
|
|
955
|
+
if (block.type !== "text") continue;
|
|
956
|
+
draft.blocks.push(block.text);
|
|
957
|
+
draft.partial = "";
|
|
958
|
+
}
|
|
959
|
+
if (textOf(draft)) update.messages.push(toMessage(draft));
|
|
960
|
+
if (message.error === "authentication_failed") update.unauthorized = "Claude Code is not signed in. Run `claude` and log in.";
|
|
961
|
+
break;
|
|
962
|
+
}
|
|
963
|
+
case "result":
|
|
964
|
+
this.#finish(update);
|
|
965
|
+
update.turnEnded = true;
|
|
966
|
+
if (message.subtype === "success" && !message.is_error) update.status = (message.queued_turn_count ?? 0) > 0 ? { status: "working" } : { status: "idle" };
|
|
967
|
+
else update.status = {
|
|
968
|
+
status: "error",
|
|
969
|
+
detail: (message.subtype === "success" ? message.result : message.errors.join("; ") || message.subtype.replaceAll("_", " ")) || void 0
|
|
970
|
+
};
|
|
971
|
+
break;
|
|
972
|
+
case "system": if (message.subtype === "session_state_changed") {
|
|
973
|
+
if (message.state === "running") update.status = { status: "working" };
|
|
974
|
+
else if (message.state === "requires_action") update.status = {
|
|
975
|
+
status: "waiting",
|
|
976
|
+
detail: "Claude Code is waiting for approval"
|
|
977
|
+
};
|
|
978
|
+
else if (this.#status.status !== "error") update.status = { status: "idle" };
|
|
979
|
+
} else if (message.subtype === "api_retry") update.status = {
|
|
980
|
+
status: "working",
|
|
981
|
+
detail: `Retrying (${message.attempt}/${message.max_retries}): ${message.error}`
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
if (update.status) this.#status = update.status;
|
|
985
|
+
return update;
|
|
986
|
+
}
|
|
987
|
+
/** Mark everything still streaming as done, e.g. after an interrupt. */
|
|
988
|
+
finish() {
|
|
989
|
+
const update = { messages: [] };
|
|
990
|
+
this.#finish(update);
|
|
991
|
+
return update.messages;
|
|
992
|
+
}
|
|
993
|
+
#begin(id, now, update) {
|
|
994
|
+
if (this.#current && this.#current !== id) {
|
|
995
|
+
const previous = this.#drafts.get(this.#current);
|
|
996
|
+
if (previous?.streaming) {
|
|
997
|
+
previous.streaming = false;
|
|
998
|
+
if (textOf(previous)) update.messages.push(toMessage(previous));
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
this.#current = id;
|
|
1002
|
+
let draft = this.#drafts.get(id);
|
|
1003
|
+
if (!draft) {
|
|
1004
|
+
draft = {
|
|
1005
|
+
id,
|
|
1006
|
+
createdAt: now,
|
|
1007
|
+
blocks: [],
|
|
1008
|
+
partial: "",
|
|
1009
|
+
streaming: true
|
|
1010
|
+
};
|
|
1011
|
+
this.#drafts.set(id, draft);
|
|
1012
|
+
}
|
|
1013
|
+
return draft;
|
|
1014
|
+
}
|
|
1015
|
+
#currentDraft() {
|
|
1016
|
+
return this.#current ? this.#drafts.get(this.#current) : void 0;
|
|
1017
|
+
}
|
|
1018
|
+
#finish(update) {
|
|
1019
|
+
for (const draft of this.#drafts.values()) {
|
|
1020
|
+
if (!draft.streaming) continue;
|
|
1021
|
+
draft.streaming = false;
|
|
1022
|
+
if (draft.partial) {
|
|
1023
|
+
draft.blocks.push(draft.partial);
|
|
1024
|
+
draft.partial = "";
|
|
1025
|
+
}
|
|
1026
|
+
if (textOf(draft)) update.messages.push(toMessage(draft));
|
|
1027
|
+
}
|
|
1028
|
+
this.#drafts.clear();
|
|
1029
|
+
this.#current = void 0;
|
|
1030
|
+
}
|
|
1031
|
+
};
|
|
1032
|
+
/** A session's conversation as stored by Claude Code, in the shape the overlay shows. */
|
|
1033
|
+
function messagesFromTranscript(entries, fallbackTime = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
1034
|
+
const messages = [];
|
|
1035
|
+
const assistants = /* @__PURE__ */ new Map();
|
|
1036
|
+
for (const entry of entries) {
|
|
1037
|
+
if (entry.parent_tool_use_id) continue;
|
|
1038
|
+
const createdAt = entry.timestamp ?? fallbackTime;
|
|
1039
|
+
const body = entry.message;
|
|
1040
|
+
if (entry.type === "user") {
|
|
1041
|
+
const text = userText(body?.content);
|
|
1042
|
+
if (text) messages.push({
|
|
1043
|
+
id: entry.uuid,
|
|
1044
|
+
role: "user",
|
|
1045
|
+
text,
|
|
1046
|
+
streaming: false,
|
|
1047
|
+
createdAt
|
|
1048
|
+
});
|
|
1049
|
+
} else if (entry.type === "assistant") {
|
|
1050
|
+
const text = blockText(body?.content);
|
|
1051
|
+
if (!text) continue;
|
|
1052
|
+
const id = body?.id ?? entry.uuid;
|
|
1053
|
+
const existing = assistants.get(id);
|
|
1054
|
+
if (existing) existing.text = `${existing.text}\n\n${text}`;
|
|
1055
|
+
else {
|
|
1056
|
+
const message = {
|
|
1057
|
+
id,
|
|
1058
|
+
role: "assistant",
|
|
1059
|
+
text,
|
|
1060
|
+
streaming: false,
|
|
1061
|
+
createdAt
|
|
1062
|
+
};
|
|
1063
|
+
assistants.set(id, message);
|
|
1064
|
+
messages.push(message);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
return messages;
|
|
1069
|
+
}
|
|
1070
|
+
/** Text the user typed; tool results ride on user messages too and are skipped. */
|
|
1071
|
+
function userText(content) {
|
|
1072
|
+
if (typeof content === "string") return content;
|
|
1073
|
+
if (!Array.isArray(content)) return "";
|
|
1074
|
+
if (content.some((block) => block?.type === "tool_result")) return "";
|
|
1075
|
+
return blockText(content);
|
|
1076
|
+
}
|
|
1077
|
+
function blockText(content) {
|
|
1078
|
+
if (!Array.isArray(content)) return "";
|
|
1079
|
+
return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).filter((text) => text.trim()).join("\n\n");
|
|
1080
|
+
}
|
|
1081
|
+
function textOf(draft) {
|
|
1082
|
+
return [...draft.blocks, draft.partial].filter((text) => text.trim()).join("\n\n");
|
|
1083
|
+
}
|
|
1084
|
+
function toMessage(draft) {
|
|
1085
|
+
return {
|
|
1086
|
+
id: draft.id,
|
|
1087
|
+
role: "assistant",
|
|
1088
|
+
text: textOf(draft),
|
|
1089
|
+
streaming: draft.streaming,
|
|
1090
|
+
createdAt: draft.createdAt
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
//#endregion
|
|
1094
|
+
//#region ../provider-claude-code/src/claude-code-provider.ts
|
|
1095
|
+
const DEFAULT_IDLE_CLOSE_MS = 6e5;
|
|
1096
|
+
/**
|
|
1097
|
+
* Runs Claude Code through the Agent SDK. Unlike T3 Code there is no server
|
|
1098
|
+
* holding the conversation: the daemon hosts one Claude Code process per
|
|
1099
|
+
* active session and Claude Code stores the transcripts, so threads are
|
|
1100
|
+
* Claude Code sessions (`claude --resume <id>` opens one in a terminal).
|
|
1101
|
+
*/
|
|
1102
|
+
var ClaudeCodeProvider = class {
|
|
1103
|
+
id = "claude-code";
|
|
1104
|
+
label = "Claude Code";
|
|
1105
|
+
#options;
|
|
1106
|
+
#info = {
|
|
1107
|
+
id: "claude-code",
|
|
1108
|
+
label: "Claude Code",
|
|
1109
|
+
state: "connecting"
|
|
1110
|
+
};
|
|
1111
|
+
#infoListeners = /* @__PURE__ */ new Set();
|
|
1112
|
+
#sdk;
|
|
1113
|
+
#workspace;
|
|
1114
|
+
#sessions = /* @__PURE__ */ new Map();
|
|
1115
|
+
#disposed = false;
|
|
1116
|
+
constructor(options) {
|
|
1117
|
+
this.#options = options;
|
|
1118
|
+
}
|
|
1119
|
+
async start() {
|
|
1120
|
+
try {
|
|
1121
|
+
await this.#load();
|
|
1122
|
+
const workspace = await this.#workspaceRoot();
|
|
1123
|
+
this.#setInfo({
|
|
1124
|
+
state: "ready",
|
|
1125
|
+
target: basename(workspace)
|
|
1126
|
+
});
|
|
1127
|
+
this.#log(`Claude Code ready in ${workspace}`);
|
|
1128
|
+
} catch (error) {
|
|
1129
|
+
this.#sdk = void 0;
|
|
1130
|
+
this.#setInfo({
|
|
1131
|
+
state: "unavailable",
|
|
1132
|
+
detail: errorMessage$1(error)
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
info() {
|
|
1137
|
+
return this.#info;
|
|
1138
|
+
}
|
|
1139
|
+
onInfoChange(listener) {
|
|
1140
|
+
this.#infoListeners.add(listener);
|
|
1141
|
+
return () => this.#infoListeners.delete(listener);
|
|
1142
|
+
}
|
|
1143
|
+
async listThreads() {
|
|
1144
|
+
const [sdk, workspace] = await Promise.all([this.#load(), this.#workspaceRoot()]);
|
|
1145
|
+
const threads = (await sdk.listSessions({
|
|
1146
|
+
dir: workspace,
|
|
1147
|
+
includeWorktrees: false
|
|
1148
|
+
})).sort((a, b) => b.lastModified - a.lastModified).map((session) => ({
|
|
1149
|
+
id: session.sessionId,
|
|
1150
|
+
title: session.customTitle ?? session.summary,
|
|
1151
|
+
status: this.#status(session.sessionId).status,
|
|
1152
|
+
updatedAt: new Date(session.lastModified).toISOString(),
|
|
1153
|
+
...session.gitBranch ? { branch: session.gitBranch } : {},
|
|
1154
|
+
agent: "claudeAgent"
|
|
1155
|
+
}));
|
|
1156
|
+
return {
|
|
1157
|
+
project: { name: basename(workspace) },
|
|
1158
|
+
threads
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
threadUrl() {}
|
|
1162
|
+
async createThread(input) {
|
|
1163
|
+
const session = this.#session(randomUUID());
|
|
1164
|
+
session.hydrated = Promise.resolve();
|
|
1165
|
+
await this.#startRun(session, {
|
|
1166
|
+
sessionId: session.id,
|
|
1167
|
+
title: input.title
|
|
1168
|
+
});
|
|
1169
|
+
this.#send(session, input.text, input.attachments);
|
|
1170
|
+
return { providerThreadId: session.id };
|
|
1171
|
+
}
|
|
1172
|
+
async sendMessage(input) {
|
|
1173
|
+
const session = this.#session(input.providerThreadId);
|
|
1174
|
+
if (!session.run) await this.#startRun(session, { resume: session.id });
|
|
1175
|
+
this.#send(session, input.text, input.attachments);
|
|
1176
|
+
}
|
|
1177
|
+
async interrupt(providerThreadId) {
|
|
1178
|
+
const run = this.#sessions.get(providerThreadId)?.run;
|
|
1179
|
+
if (!run) return;
|
|
1180
|
+
run.interrupted = true;
|
|
1181
|
+
await run.query.interrupt();
|
|
1182
|
+
}
|
|
1183
|
+
watch(providerThreadId, sink) {
|
|
1184
|
+
const session = this.#session(providerThreadId);
|
|
1185
|
+
session.sink = sink;
|
|
1186
|
+
this.#hydrate(session).then((gone) => {
|
|
1187
|
+
if (session.sink !== sink) return;
|
|
1188
|
+
if (gone) return sink.gone();
|
|
1189
|
+
const messages = [...session.messages.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
1190
|
+
for (const message of messages) sink.message(message);
|
|
1191
|
+
const status = this.#status(session.id);
|
|
1192
|
+
sink.status(status.status, status.detail);
|
|
1193
|
+
}, (error) => this.#log(`Couldn't load session ${providerThreadId}: ${errorMessage$1(error)}`));
|
|
1194
|
+
return () => {
|
|
1195
|
+
if (session.sink === sink) session.sink = void 0;
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
async dispose() {
|
|
1199
|
+
this.#disposed = true;
|
|
1200
|
+
for (const session of this.#sessions.values()) this.#close(session);
|
|
1201
|
+
this.#sessions.clear();
|
|
1202
|
+
}
|
|
1203
|
+
/** Sessions without a running process are idle (or ended in an error). */
|
|
1204
|
+
#status(id) {
|
|
1205
|
+
const session = this.#sessions.get(id);
|
|
1206
|
+
if (!session) return { status: "idle" };
|
|
1207
|
+
const status = session.tracker.status();
|
|
1208
|
+
return session.run || status.status === "error" ? status : { status: "idle" };
|
|
1209
|
+
}
|
|
1210
|
+
#session(id) {
|
|
1211
|
+
let session = this.#sessions.get(id);
|
|
1212
|
+
if (!session) {
|
|
1213
|
+
session = {
|
|
1214
|
+
id,
|
|
1215
|
+
tracker: new TurnTracker(),
|
|
1216
|
+
messages: /* @__PURE__ */ new Map()
|
|
1217
|
+
};
|
|
1218
|
+
this.#sessions.set(id, session);
|
|
1219
|
+
}
|
|
1220
|
+
return session;
|
|
1221
|
+
}
|
|
1222
|
+
#emit(session, message) {
|
|
1223
|
+
session.messages.set(message.id, message);
|
|
1224
|
+
session.sink?.message(message);
|
|
1225
|
+
}
|
|
1226
|
+
/** Load the transcript Claude Code saved, once. Resolves true when the session doesn't exist. */
|
|
1227
|
+
async #hydrate(session) {
|
|
1228
|
+
if (!session.hydrated) {
|
|
1229
|
+
session.hydrated = (async () => {
|
|
1230
|
+
const [sdk, workspace] = await Promise.all([this.#load(), this.#workspaceRoot()]);
|
|
1231
|
+
const entries = await sdk.getSessionMessages(session.id, { dir: workspace });
|
|
1232
|
+
for (const message of messagesFromTranscript(entries)) if (!session.messages.has(message.id)) session.messages.set(message.id, message);
|
|
1233
|
+
if (entries.length === 0 && !session.run) session.missing = !await sdk.getSessionInfo(session.id, { dir: workspace });
|
|
1234
|
+
})();
|
|
1235
|
+
session.hydrated.catch(() => {
|
|
1236
|
+
session.hydrated = void 0;
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
await session.hydrated;
|
|
1240
|
+
return session.missing === true && !session.run;
|
|
1241
|
+
}
|
|
1242
|
+
async #startRun(session, start) {
|
|
1243
|
+
if (this.#disposed) throw new Error("Tencil is shutting down");
|
|
1244
|
+
const [sdk, workspace] = await Promise.all([this.#load(), this.#workspaceRoot()]);
|
|
1245
|
+
if (session.run) return;
|
|
1246
|
+
const permissionMode = this.#options.permissionMode ?? "bypassPermissions";
|
|
1247
|
+
const input = new InputQueue();
|
|
1248
|
+
const run = {
|
|
1249
|
+
query: sdk.query({
|
|
1250
|
+
prompt: input,
|
|
1251
|
+
options: {
|
|
1252
|
+
...start,
|
|
1253
|
+
cwd: workspace,
|
|
1254
|
+
systemPrompt: {
|
|
1255
|
+
type: "preset",
|
|
1256
|
+
preset: "claude_code"
|
|
1257
|
+
},
|
|
1258
|
+
includePartialMessages: true,
|
|
1259
|
+
permissionMode,
|
|
1260
|
+
allowDangerouslySkipPermissions: permissionMode === "bypassPermissions",
|
|
1261
|
+
permissionPrompts: "none",
|
|
1262
|
+
...this.#options.model ? { model: this.#options.model } : {},
|
|
1263
|
+
stderr: (data) => this.#log(data.trimEnd())
|
|
1264
|
+
}
|
|
1265
|
+
}),
|
|
1266
|
+
input
|
|
1267
|
+
};
|
|
1268
|
+
session.run = run;
|
|
1269
|
+
session.tracker.setStatus({ status: "working" });
|
|
1270
|
+
this.#consume(session, run);
|
|
1271
|
+
}
|
|
1272
|
+
async #consume(session, run) {
|
|
1273
|
+
let failure;
|
|
1274
|
+
try {
|
|
1275
|
+
for await (const message of run.query) {
|
|
1276
|
+
const update = session.tracker.apply(message);
|
|
1277
|
+
for (const m of update.messages) this.#emit(session, m);
|
|
1278
|
+
if (update.unauthorized) this.#setInfo({
|
|
1279
|
+
state: "unauthorized",
|
|
1280
|
+
detail: update.unauthorized
|
|
1281
|
+
});
|
|
1282
|
+
if (update.turnEnded && run.interrupted) {
|
|
1283
|
+
run.interrupted = false;
|
|
1284
|
+
session.tracker.setStatus({ status: "idle" });
|
|
1285
|
+
session.sink?.status("idle");
|
|
1286
|
+
} else if (update.status) session.sink?.status(update.status.status, update.status.detail);
|
|
1287
|
+
if (update.turnEnded) this.#scheduleIdleClose(session, run);
|
|
1288
|
+
}
|
|
1289
|
+
} catch (error) {
|
|
1290
|
+
failure = errorMessage$1(error);
|
|
1291
|
+
}
|
|
1292
|
+
if (session.run !== run) return;
|
|
1293
|
+
session.run = void 0;
|
|
1294
|
+
clearTimeout(run.idleTimer);
|
|
1295
|
+
run.input.close();
|
|
1296
|
+
for (const m of session.tracker.finish()) this.#emit(session, m);
|
|
1297
|
+
if (session.tracker.status().status === "working" || failure) {
|
|
1298
|
+
const status = {
|
|
1299
|
+
status: "error",
|
|
1300
|
+
detail: failure ?? "Claude Code stopped before the turn finished"
|
|
1301
|
+
};
|
|
1302
|
+
session.tracker.setStatus(status);
|
|
1303
|
+
session.sink?.status(status.status, status.detail);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
#send(session, text, attachments) {
|
|
1307
|
+
const run = session.run;
|
|
1308
|
+
if (!run) throw new Error("Claude Code session is not running");
|
|
1309
|
+
clearTimeout(run.idleTimer);
|
|
1310
|
+
const uuid = randomUUID();
|
|
1311
|
+
this.#emit(session, {
|
|
1312
|
+
id: uuid,
|
|
1313
|
+
role: "user",
|
|
1314
|
+
text,
|
|
1315
|
+
streaming: false,
|
|
1316
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1317
|
+
});
|
|
1318
|
+
session.tracker.setStatus({ status: "working" });
|
|
1319
|
+
session.sink?.status("working");
|
|
1320
|
+
run.input.push({
|
|
1321
|
+
type: "user",
|
|
1322
|
+
message: {
|
|
1323
|
+
role: "user",
|
|
1324
|
+
content: [...attachments.map(imageBlock), {
|
|
1325
|
+
type: "text",
|
|
1326
|
+
text
|
|
1327
|
+
}]
|
|
1328
|
+
},
|
|
1329
|
+
parent_tool_use_id: null,
|
|
1330
|
+
uuid,
|
|
1331
|
+
session_id: session.id
|
|
1332
|
+
});
|
|
1333
|
+
}
|
|
1334
|
+
/** Each run is a Claude Code process; let idle ones go and resume on the next message. */
|
|
1335
|
+
#scheduleIdleClose(session, run) {
|
|
1336
|
+
clearTimeout(run.idleTimer);
|
|
1337
|
+
if (session.tracker.status().status === "working") return;
|
|
1338
|
+
run.idleTimer = setTimeout(() => {
|
|
1339
|
+
if (session.run === run) this.#close(session);
|
|
1340
|
+
}, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS);
|
|
1341
|
+
run.idleTimer.unref?.();
|
|
1342
|
+
}
|
|
1343
|
+
#close(session) {
|
|
1344
|
+
const run = session.run;
|
|
1345
|
+
if (!run) return;
|
|
1346
|
+
session.run = void 0;
|
|
1347
|
+
clearTimeout(run.idleTimer);
|
|
1348
|
+
run.input.close();
|
|
1349
|
+
run.query.close();
|
|
1350
|
+
}
|
|
1351
|
+
#load() {
|
|
1352
|
+
if (this.#options.sdk) return Promise.resolve(this.#options.sdk);
|
|
1353
|
+
this.#sdk ??= loadAgentSdk({
|
|
1354
|
+
installDir: this.#options.installDir,
|
|
1355
|
+
onInstall: () => {
|
|
1356
|
+
this.#setInfo({
|
|
1357
|
+
state: "connecting",
|
|
1358
|
+
detail: "Installing Claude Code support…"
|
|
1359
|
+
});
|
|
1360
|
+
this.#log(`Installing the Claude Agent SDK into ${this.#options.installDir}`);
|
|
1361
|
+
}
|
|
1362
|
+
});
|
|
1363
|
+
return this.#sdk;
|
|
1364
|
+
}
|
|
1365
|
+
/** The repository root, so Claude Code sees the whole project and its CLAUDE.md. */
|
|
1366
|
+
#workspaceRoot() {
|
|
1367
|
+
this.#workspace ??= (async () => {
|
|
1368
|
+
const root = await realpath(this.#options.projectRoot).catch(() => this.#options.projectRoot);
|
|
1369
|
+
return await repositoryRoot$1(root) ?? root;
|
|
1370
|
+
})();
|
|
1371
|
+
return this.#workspace;
|
|
1372
|
+
}
|
|
1373
|
+
#setInfo(next) {
|
|
1374
|
+
const info = {
|
|
1375
|
+
id: this.id,
|
|
1376
|
+
label: this.label,
|
|
1377
|
+
...next
|
|
1378
|
+
};
|
|
1379
|
+
if (info.state === this.#info.state && info.detail === this.#info.detail && info.target === this.#info.target) return;
|
|
1380
|
+
this.#info = info;
|
|
1381
|
+
for (const listener of this.#infoListeners) listener(info);
|
|
1382
|
+
}
|
|
1383
|
+
#log(message) {
|
|
1384
|
+
this.#options.log?.(message);
|
|
1385
|
+
}
|
|
1386
|
+
};
|
|
1387
|
+
function imageBlock(attachment) {
|
|
1388
|
+
const data = attachment.dataUrl.slice(attachment.dataUrl.indexOf(",") + 1);
|
|
1389
|
+
return {
|
|
1390
|
+
type: "image",
|
|
1391
|
+
source: {
|
|
1392
|
+
type: "base64",
|
|
1393
|
+
media_type: attachment.mimeType,
|
|
1394
|
+
data
|
|
1395
|
+
}
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
/** The nearest folder at or above `dir` with a `.git` entry, if any. */
|
|
1399
|
+
async function repositoryRoot$1(dir) {
|
|
1400
|
+
for (let current = dir;; current = dirname(current)) {
|
|
1401
|
+
if (await exists$1(join(current, ".git"))) return current;
|
|
1402
|
+
if (dirname(current) === current) return void 0;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
const exists$1 = (path) => access(path).then(() => true, () => false);
|
|
1406
|
+
function errorMessage$1(error) {
|
|
1407
|
+
return error instanceof Error ? error.message : String(error);
|
|
1408
|
+
}
|
|
1409
|
+
//#endregion
|
|
1410
|
+
//#region ../provider-claude-code/src/projects.ts
|
|
1411
|
+
/** Folders Claude Code has sessions in, most recently used first. */
|
|
1412
|
+
async function listClaudeCodeProjects(options) {
|
|
1413
|
+
const sessions = await (options.sdk ?? await loadAgentSdk({ installDir: options.installDir })).listSessions({ includeProgrammatic: false });
|
|
1414
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1415
|
+
const projects = [];
|
|
1416
|
+
for (const session of sessions.sort((a, b) => b.lastModified - a.lastModified)) {
|
|
1417
|
+
if (!session.cwd || seen.has(session.cwd)) continue;
|
|
1418
|
+
seen.add(session.cwd);
|
|
1419
|
+
projects.push({
|
|
1420
|
+
workspaceRoot: session.cwd,
|
|
1421
|
+
title: basename(session.cwd)
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
return projects;
|
|
1425
|
+
}
|
|
1426
|
+
//#endregion
|
|
1427
|
+
//#region ../provider-t3code/src/auth.ts
|
|
1428
|
+
const DEFAULT_T3_URL = "http://127.0.0.1:3773";
|
|
1429
|
+
/** Scopes Tencil needs: read thread state and launch/steer threads. */
|
|
1430
|
+
const SCOPES = "orchestration:read orchestration:operate";
|
|
1431
|
+
/**
|
|
1432
|
+
* Accepts what T3 Code hands out in Settings → Connections or `t3 pair`:
|
|
1433
|
+
* a pairing URL (`http://host:3773/pair#token=…`, token may also be in the
|
|
1434
|
+
* query string) or a bare pairing code combined with `fallbackBaseUrl`.
|
|
1435
|
+
*/
|
|
1436
|
+
function parsePairingInput(input, fallbackBaseUrl) {
|
|
1437
|
+
const trimmed = input.trim();
|
|
1438
|
+
if (!/^https?:\/\//i.test(trimmed)) {
|
|
1439
|
+
if (!trimmed) throw new Error("Pairing code is empty");
|
|
1440
|
+
return {
|
|
1441
|
+
baseUrl: normalizeBaseUrl(fallbackBaseUrl),
|
|
1442
|
+
credential: trimmed
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
const url = new URL(trimmed);
|
|
1446
|
+
const credential = new URLSearchParams(url.hash.replace(/^#/, "")).get("token")?.trim() || url.searchParams.get("token")?.trim();
|
|
1447
|
+
if (!credential) throw new Error("Pairing link has no token. Copy the full link from T3 Code.");
|
|
1448
|
+
const hostedBackend = url.searchParams.get("host")?.trim();
|
|
1449
|
+
return {
|
|
1450
|
+
baseUrl: normalizeBaseUrl(hostedBackend || url.origin),
|
|
1451
|
+
credential
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
function normalizeBaseUrl(raw) {
|
|
1455
|
+
return new URL(/^https?:\/\//i.test(raw) ? raw : `http://${raw}`).origin;
|
|
1456
|
+
}
|
|
1457
|
+
async function exchangePairingCredential(target, clientLabel = "Tencil") {
|
|
1458
|
+
const body = new URLSearchParams({
|
|
1459
|
+
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
|
|
1460
|
+
subject_token: target.credential,
|
|
1461
|
+
subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
|
|
1462
|
+
requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
|
1463
|
+
scope: SCOPES,
|
|
1464
|
+
client_label: clientLabel,
|
|
1465
|
+
client_device_type: "desktop"
|
|
1466
|
+
});
|
|
1467
|
+
const response = await fetch(`${target.baseUrl}/oauth/token`, {
|
|
1468
|
+
signal: AbortSignal.timeout(15e3),
|
|
1469
|
+
method: "POST",
|
|
1470
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
1471
|
+
body
|
|
1472
|
+
});
|
|
1473
|
+
if (!response.ok) {
|
|
1474
|
+
const body = await response.json().catch(() => null);
|
|
1475
|
+
const reason = body?.error_description ?? body?.error;
|
|
1476
|
+
throw new Error(`T3 Code rejected the pairing code (${response.status}${reason ? `: ${reason}` : ""}). Codes work once and expire after about 5 minutes; use the \`Token:\` value, not the link id.`);
|
|
1477
|
+
}
|
|
1478
|
+
const result = await response.json();
|
|
1479
|
+
if (result.token_type !== "Bearer") throw new Error(`Unsupported token type "${result.token_type}"`);
|
|
1480
|
+
return {
|
|
1481
|
+
token: result.access_token,
|
|
1482
|
+
scope: result.scope,
|
|
1483
|
+
expiresAt: new Date(Date.now() + result.expires_in * 1e3).toISOString()
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Mint a pairing code on a local T3 Code by running the `t3` CLI that matches
|
|
1488
|
+
* the server's own version (mismatched CLIs may migrate the database).
|
|
1489
|
+
* Returns undefined when the server isn't local or the CLI fails.
|
|
1490
|
+
*/
|
|
1491
|
+
/**
|
|
1492
|
+
* The environment minus the lowercase `npm_*` variables an outer npm or npx
|
|
1493
|
+
* passes down: under `npx --package <spec> tencil`, `npm_config_package` makes
|
|
1494
|
+
* a nested `npx t3` run that package instead. Variables the user set
|
|
1495
|
+
* (`NPM_CONFIG_REGISTRY`) are uppercase and stay.
|
|
1496
|
+
*/
|
|
1497
|
+
function withoutNpmEnv(env = process.env) {
|
|
1498
|
+
return Object.fromEntries(Object.entries(env).filter(([key]) => !key.startsWith("npm_")));
|
|
1499
|
+
}
|
|
1500
|
+
async function createLocalPairingCode(baseUrl, baseDir = process.env.T3CODE_HOME ?? join(homedir(), ".t3")) {
|
|
1501
|
+
const { hostname } = new URL(baseUrl);
|
|
1502
|
+
if (![
|
|
1503
|
+
"localhost",
|
|
1504
|
+
"127.0.0.1",
|
|
1505
|
+
"[::1]"
|
|
1506
|
+
].includes(hostname)) return void 0;
|
|
1507
|
+
const response = await fetch(new URL("/.well-known/t3/environment", baseUrl), { signal: AbortSignal.timeout(8e3) }).catch(() => null);
|
|
1508
|
+
if (!response?.ok) return void 0;
|
|
1509
|
+
const { serverVersion } = await response.json();
|
|
1510
|
+
if (!serverVersion) return void 0;
|
|
1511
|
+
const { spawnSync } = await import("node:child_process");
|
|
1512
|
+
const args = [
|
|
1513
|
+
"auth",
|
|
1514
|
+
"pairing",
|
|
1515
|
+
"create",
|
|
1516
|
+
"--base-dir",
|
|
1517
|
+
baseDir
|
|
1518
|
+
];
|
|
1519
|
+
const installed = join(baseDir, "runtime", "versions", serverVersion, "t3");
|
|
1520
|
+
const result = existsSync(installed) ? spawnSync(installed, args, {
|
|
1521
|
+
encoding: "utf8",
|
|
1522
|
+
timeout: 3e4,
|
|
1523
|
+
env: withoutNpmEnv()
|
|
1524
|
+
}) : spawnSync(process.platform === "win32" ? "npx.cmd" : "npx", [
|
|
1525
|
+
"-y",
|
|
1526
|
+
`t3@${serverVersion}`,
|
|
1527
|
+
...args
|
|
1528
|
+
], {
|
|
1529
|
+
encoding: "utf8",
|
|
1530
|
+
timeout: 12e4,
|
|
1531
|
+
shell: process.platform === "win32",
|
|
1532
|
+
env: withoutNpmEnv()
|
|
1533
|
+
});
|
|
1534
|
+
return `${result.stdout ?? ""}\n${result.stderr ?? ""}`.match(/^Token:\s*(\S+)/m)?.[1];
|
|
1535
|
+
}
|
|
1536
|
+
async function requestWebSocketTicket(baseUrl, token, timeoutMs = 8e3) {
|
|
1537
|
+
const response = await fetch(`${baseUrl}/api/auth/websocket-ticket`, {
|
|
1538
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
1539
|
+
method: "POST",
|
|
1540
|
+
headers: { authorization: `Bearer ${token}` }
|
|
1541
|
+
});
|
|
1542
|
+
if (response.status === 401 || response.status === 403) throw new UnauthorizedError();
|
|
1543
|
+
if (!response.ok) throw new Error(`WebSocket ticket request failed (${response.status})`);
|
|
1544
|
+
const { ticket } = await response.json();
|
|
1545
|
+
return ticket;
|
|
1546
|
+
}
|
|
1547
|
+
var UnauthorizedError = class extends Error {
|
|
1548
|
+
constructor(message = "T3 Code rejected the stored token. Run `tencil connect` to pair again.") {
|
|
1549
|
+
super(message);
|
|
1550
|
+
this.name = "UnauthorizedError";
|
|
1551
|
+
}
|
|
1552
|
+
};
|
|
1553
|
+
/** Credentials live outside the project so they never end up in git. */
|
|
1554
|
+
var CredentialStore = class {
|
|
1555
|
+
path;
|
|
1556
|
+
constructor(path = join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "tencil", "credentials.json")) {
|
|
1557
|
+
this.path = path;
|
|
1558
|
+
}
|
|
1559
|
+
async get(baseUrl) {
|
|
1560
|
+
const credential = (await this.#read()).servers[credentialKey(baseUrl)];
|
|
1561
|
+
if (!credential) return void 0;
|
|
1562
|
+
if (Date.parse(credential.expiresAt) <= Date.now()) return void 0;
|
|
1563
|
+
return credential;
|
|
1564
|
+
}
|
|
1565
|
+
async lastBaseUrl() {
|
|
1566
|
+
return (await this.#read()).lastBaseUrl;
|
|
1567
|
+
}
|
|
1568
|
+
async set(baseUrl, credential) {
|
|
1569
|
+
const file = await this.#read();
|
|
1570
|
+
file.servers[credentialKey(baseUrl)] = credential;
|
|
1571
|
+
file.lastBaseUrl = normalizeBaseUrl(baseUrl);
|
|
1572
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
1573
|
+
await writeFile(this.path, `${JSON.stringify(file, null, 2)}\n`, { mode: 384 });
|
|
1574
|
+
await chmod(this.path, 384);
|
|
1575
|
+
}
|
|
1576
|
+
async #read() {
|
|
1577
|
+
try {
|
|
1578
|
+
const parsed = JSON.parse(await readFile(this.path, "utf8"));
|
|
1579
|
+
return {
|
|
1580
|
+
lastBaseUrl: parsed.lastBaseUrl,
|
|
1581
|
+
servers: parsed.servers ?? {}
|
|
1582
|
+
};
|
|
1583
|
+
} catch {
|
|
1584
|
+
return { servers: {} };
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
/** `localhost`, `127.0.0.1` and `[::1]` reach the same server; share one credential. */
|
|
1589
|
+
function credentialKey(baseUrl) {
|
|
1590
|
+
const url = new URL(normalizeBaseUrl(baseUrl));
|
|
1591
|
+
if (url.hostname === "localhost" || url.hostname === "[::1]" || url.hostname.startsWith("127.")) url.hostname = "127.0.0.1";
|
|
1592
|
+
return url.origin;
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* The T3 Code projects on this machine, for the "which project is this
|
|
1596
|
+
* page?" picker. Uses the paired token; returns [] when not paired or offline.
|
|
1597
|
+
*/
|
|
1598
|
+
async function listT3Projects(options = {}) {
|
|
1599
|
+
const credentials = options.credentials ?? new CredentialStore();
|
|
1600
|
+
const baseUrl = normalizeBaseUrl(options.baseUrl ?? await credentials.lastBaseUrl() ?? "http://127.0.0.1:3773");
|
|
1601
|
+
const token = options.token ?? (await credentials.get(baseUrl))?.token;
|
|
1602
|
+
if (!token) return [];
|
|
1603
|
+
try {
|
|
1604
|
+
const response = await fetch(`${baseUrl}/api/orchestration/shell`, {
|
|
1605
|
+
signal: AbortSignal.timeout(8e3),
|
|
1606
|
+
headers: {
|
|
1607
|
+
authorization: `Bearer ${token}`,
|
|
1608
|
+
"x-t3-orchestration-protocol": "2"
|
|
1609
|
+
}
|
|
1610
|
+
});
|
|
1611
|
+
if (!response.ok) return [];
|
|
1612
|
+
return (await response.json()).projects.map(({ id, title, workspaceRoot }) => ({
|
|
1613
|
+
id,
|
|
1614
|
+
title,
|
|
1615
|
+
workspaceRoot
|
|
1616
|
+
}));
|
|
1617
|
+
} catch {
|
|
1618
|
+
return [];
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
//#endregion
|
|
1622
|
+
//#region ../provider-t3code/src/protocols/adapter.ts
|
|
1623
|
+
function decodedSize(dataUrl) {
|
|
1624
|
+
return Buffer.from(dataUrl.split(",", 2)[1] ?? "", "base64").byteLength;
|
|
1625
|
+
}
|
|
1626
|
+
//#endregion
|
|
1627
|
+
//#region ../provider-t3code/src/protocols/v1.ts
|
|
1628
|
+
/**
|
|
1629
|
+
* Orchestration V1, spoken by every released T3 Code build (≤ 0.0.45). A
|
|
1630
|
+
* `thread.turn.start` with `bootstrap.createThread` creates the thread and
|
|
1631
|
+
* starts its first turn atomically; images ride inline as data URLs.
|
|
1632
|
+
*/
|
|
1633
|
+
const v1 = {
|
|
1634
|
+
version: 1,
|
|
1635
|
+
async createProject(socket, input) {
|
|
1636
|
+
await socket.request("orchestration.dispatchCommand", {
|
|
1637
|
+
type: "project.create",
|
|
1638
|
+
commandId: randomUUID(),
|
|
1639
|
+
projectId: input.projectId,
|
|
1640
|
+
title: input.title,
|
|
1641
|
+
workspaceRoot: input.workspaceRoot,
|
|
1642
|
+
createdAt: now()
|
|
1643
|
+
});
|
|
1644
|
+
},
|
|
1645
|
+
async startThread(socket, input) {
|
|
1646
|
+
const createdAt = now();
|
|
1647
|
+
await socket.request("orchestration.dispatchCommand", {
|
|
1648
|
+
type: "thread.turn.start",
|
|
1649
|
+
commandId: randomUUID(),
|
|
1650
|
+
threadId: input.threadId,
|
|
1651
|
+
message: {
|
|
1652
|
+
messageId: randomUUID(),
|
|
1653
|
+
role: "user",
|
|
1654
|
+
text: input.text,
|
|
1655
|
+
attachments: uploads(input.attachments)
|
|
1656
|
+
},
|
|
1657
|
+
modelSelection: input.modelSelection,
|
|
1658
|
+
titleSeed: input.title,
|
|
1659
|
+
runtimeMode: input.runtimeMode,
|
|
1660
|
+
interactionMode: input.interactionMode,
|
|
1661
|
+
bootstrap: { createThread: {
|
|
1662
|
+
projectId: input.projectId,
|
|
1663
|
+
title: input.title,
|
|
1664
|
+
modelSelection: input.modelSelection,
|
|
1665
|
+
runtimeMode: input.runtimeMode,
|
|
1666
|
+
interactionMode: input.interactionMode,
|
|
1667
|
+
branch: null,
|
|
1668
|
+
worktreePath: null,
|
|
1669
|
+
createdAt
|
|
1670
|
+
} },
|
|
1671
|
+
createdAt
|
|
1672
|
+
});
|
|
1673
|
+
},
|
|
1674
|
+
async sendMessage(socket, input) {
|
|
1675
|
+
await socket.request("orchestration.dispatchCommand", {
|
|
1676
|
+
type: "thread.turn.start",
|
|
1677
|
+
commandId: randomUUID(),
|
|
1678
|
+
threadId: input.threadId,
|
|
1679
|
+
message: {
|
|
1680
|
+
messageId: randomUUID(),
|
|
1681
|
+
role: "user",
|
|
1682
|
+
text: input.text,
|
|
1683
|
+
attachments: uploads(input.attachments)
|
|
1684
|
+
},
|
|
1685
|
+
runtimeMode: input.runtimeMode,
|
|
1686
|
+
interactionMode: input.interactionMode,
|
|
1687
|
+
createdAt: now()
|
|
1688
|
+
});
|
|
1689
|
+
},
|
|
1690
|
+
async interrupt(socket, threadId, turnId) {
|
|
1691
|
+
await socket.request("orchestration.dispatchCommand", {
|
|
1692
|
+
type: "thread.turn.interrupt",
|
|
1693
|
+
commandId: randomUUID(),
|
|
1694
|
+
threadId,
|
|
1695
|
+
turnId,
|
|
1696
|
+
createdAt: now()
|
|
1697
|
+
});
|
|
1698
|
+
},
|
|
1699
|
+
createTracker: () => new V1ThreadTracker()
|
|
1700
|
+
};
|
|
1701
|
+
function uploads(attachments) {
|
|
1702
|
+
return attachments.map((attachment) => ({
|
|
1703
|
+
type: "image",
|
|
1704
|
+
name: attachment.name,
|
|
1705
|
+
mimeType: attachment.mimeType,
|
|
1706
|
+
sizeBytes: decodedSize(attachment.dataUrl),
|
|
1707
|
+
dataUrl: attachment.dataUrl
|
|
1708
|
+
}));
|
|
1709
|
+
}
|
|
1710
|
+
function now() {
|
|
1711
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
1712
|
+
}
|
|
1713
|
+
var V1ThreadTracker = class {
|
|
1714
|
+
#messages = /* @__PURE__ */ new Map();
|
|
1715
|
+
#session = null;
|
|
1716
|
+
#latestTurn = null;
|
|
1717
|
+
/** A turn was requested but the session hasn't reported it running yet. */
|
|
1718
|
+
#pendingStart = false;
|
|
1719
|
+
#lastStatusKey = "";
|
|
1720
|
+
apply(raw) {
|
|
1721
|
+
const item = raw;
|
|
1722
|
+
const changed = [];
|
|
1723
|
+
let gone = false;
|
|
1724
|
+
if (item.kind === "snapshot") {
|
|
1725
|
+
const { thread } = item.snapshot;
|
|
1726
|
+
this.#session = thread.session ?? null;
|
|
1727
|
+
this.#latestTurn = thread.latestTurn ?? null;
|
|
1728
|
+
for (const message of thread.messages ?? []) this.#replace(message, changed);
|
|
1729
|
+
} else if (item.kind === "event") {
|
|
1730
|
+
const { type, payload } = item.event;
|
|
1731
|
+
switch (type) {
|
|
1732
|
+
case "thread.message-sent":
|
|
1733
|
+
this.#messageSent(payload, changed);
|
|
1734
|
+
break;
|
|
1735
|
+
case "thread.session-set": {
|
|
1736
|
+
const session = payload.session;
|
|
1737
|
+
this.#session = session;
|
|
1738
|
+
if (session.status === "running" || session.status === "starting" || session.status === "error") this.#pendingStart = false;
|
|
1739
|
+
break;
|
|
1740
|
+
}
|
|
1741
|
+
case "thread.turn-start-requested":
|
|
1742
|
+
this.#pendingStart = true;
|
|
1743
|
+
break;
|
|
1744
|
+
case "thread.deleted": gone = true;
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
const update = { messages: changed };
|
|
1748
|
+
if (gone) update.gone = true;
|
|
1749
|
+
const status = this.status();
|
|
1750
|
+
const key = `${status.status}:${status.detail ?? ""}`;
|
|
1751
|
+
if (key !== this.#lastStatusKey) {
|
|
1752
|
+
this.#lastStatusKey = key;
|
|
1753
|
+
update.status = status;
|
|
1754
|
+
}
|
|
1755
|
+
return update;
|
|
1756
|
+
}
|
|
1757
|
+
status() {
|
|
1758
|
+
if (this.#pendingStart) return { status: "working" };
|
|
1759
|
+
switch (this.#session?.status) {
|
|
1760
|
+
case "starting":
|
|
1761
|
+
case "running": return { status: "working" };
|
|
1762
|
+
case "error": return {
|
|
1763
|
+
status: "error",
|
|
1764
|
+
detail: this.#session.lastError ?? "Agent session failed"
|
|
1765
|
+
};
|
|
1766
|
+
case "interrupted": return {
|
|
1767
|
+
status: "idle",
|
|
1768
|
+
detail: "Stopped"
|
|
1769
|
+
};
|
|
1770
|
+
}
|
|
1771
|
+
if (this.#latestTurn?.state === "running") return { status: "working" };
|
|
1772
|
+
if (this.#latestTurn?.state === "error") return {
|
|
1773
|
+
status: "error",
|
|
1774
|
+
detail: "Turn failed"
|
|
1775
|
+
};
|
|
1776
|
+
return { status: "idle" };
|
|
1777
|
+
}
|
|
1778
|
+
activeTurnId() {
|
|
1779
|
+
return this.#session?.activeTurnId ?? (this.#latestTurn?.state === "running" ? this.#latestTurn.turnId : void 0);
|
|
1780
|
+
}
|
|
1781
|
+
/** Mirrors the server projector: streaming events carry deltas, the final one the full text. */
|
|
1782
|
+
#messageSent(payload, changed) {
|
|
1783
|
+
if (payload.role === "system") return;
|
|
1784
|
+
const existing = this.#messages.get(payload.messageId);
|
|
1785
|
+
const text = existing ? payload.streaming ? existing.text + payload.text : payload.text.length > 0 ? payload.text : existing.text : payload.text;
|
|
1786
|
+
this.#set({
|
|
1787
|
+
id: payload.messageId,
|
|
1788
|
+
role: payload.role,
|
|
1789
|
+
text,
|
|
1790
|
+
streaming: payload.streaming,
|
|
1791
|
+
createdAt: existing?.createdAt ?? payload.createdAt
|
|
1792
|
+
}, changed);
|
|
1793
|
+
}
|
|
1794
|
+
#replace(message, changed) {
|
|
1795
|
+
if (message.role === "system") return;
|
|
1796
|
+
this.#set({
|
|
1797
|
+
id: message.id,
|
|
1798
|
+
role: message.role,
|
|
1799
|
+
text: message.text,
|
|
1800
|
+
streaming: message.streaming,
|
|
1801
|
+
createdAt: message.createdAt
|
|
1802
|
+
}, changed);
|
|
1803
|
+
}
|
|
1804
|
+
#set(next, changed) {
|
|
1805
|
+
const previous = this.#messages.get(next.id);
|
|
1806
|
+
if (previous && previous.text === next.text && previous.streaming === next.streaming) return;
|
|
1807
|
+
this.#messages.set(next.id, next);
|
|
1808
|
+
const index = changed.findIndex((message) => message.id === next.id);
|
|
1809
|
+
if (index === -1) changed.push(next);
|
|
1810
|
+
else changed[index] = next;
|
|
1811
|
+
}
|
|
1812
|
+
};
|
|
1813
|
+
//#endregion
|
|
1814
|
+
//#region ../provider-t3code/src/protocols/v2.ts
|
|
1815
|
+
/**
|
|
1816
|
+
* Orchestration V2 (builds advertising `orchestrationProtocolVersion: 2`).
|
|
1817
|
+
* Threads launch atomically via `orchestration.launchThread`; images are
|
|
1818
|
+
* persisted first and referenced by id.
|
|
1819
|
+
*/
|
|
1820
|
+
const v2 = {
|
|
1821
|
+
version: 2,
|
|
1822
|
+
async createProject(socket, input) {
|
|
1823
|
+
await socket.request("projects.mutate", {
|
|
1824
|
+
type: "project.create",
|
|
1825
|
+
commandId: randomUUID(),
|
|
1826
|
+
projectId: input.projectId,
|
|
1827
|
+
title: input.title,
|
|
1828
|
+
workspaceRoot: input.workspaceRoot
|
|
1829
|
+
});
|
|
1830
|
+
},
|
|
1831
|
+
async startThread(socket, input) {
|
|
1832
|
+
const messageId = randomUUID();
|
|
1833
|
+
const attachments = await persist(socket, input.threadId, messageId, input.attachments);
|
|
1834
|
+
await socket.request("orchestration.launchThread", {
|
|
1835
|
+
commandId: randomUUID(),
|
|
1836
|
+
creationSource: "web",
|
|
1837
|
+
threadId: input.threadId,
|
|
1838
|
+
projectId: input.projectId,
|
|
1839
|
+
title: input.title,
|
|
1840
|
+
generateTitle: true,
|
|
1841
|
+
modelSelection: input.modelSelection,
|
|
1842
|
+
runtimeMode: input.runtimeMode,
|
|
1843
|
+
interactionMode: input.interactionMode,
|
|
1844
|
+
workspaceStrategy: { type: "root" },
|
|
1845
|
+
initialMessage: {
|
|
1846
|
+
messageId,
|
|
1847
|
+
text: input.text,
|
|
1848
|
+
attachments
|
|
1849
|
+
}
|
|
1850
|
+
});
|
|
1851
|
+
},
|
|
1852
|
+
async sendMessage(socket, input) {
|
|
1853
|
+
const messageId = randomUUID();
|
|
1854
|
+
const attachments = await persist(socket, input.threadId, messageId, input.attachments);
|
|
1855
|
+
await socket.request("orchestration.dispatchCommand", {
|
|
1856
|
+
type: "message.dispatch",
|
|
1857
|
+
createdBy: "user",
|
|
1858
|
+
creationSource: "web",
|
|
1859
|
+
commandId: randomUUID(),
|
|
1860
|
+
threadId: input.threadId,
|
|
1861
|
+
messageId,
|
|
1862
|
+
text: input.text,
|
|
1863
|
+
attachments,
|
|
1864
|
+
dispatchMode: { type: input.busy ? "queue_after_active" : "start_immediately" }
|
|
1865
|
+
});
|
|
1866
|
+
},
|
|
1867
|
+
async interrupt(socket, threadId, runId) {
|
|
1868
|
+
await socket.request("orchestration.dispatchCommand", {
|
|
1869
|
+
type: "run.interrupt",
|
|
1870
|
+
commandId: randomUUID(),
|
|
1871
|
+
threadId,
|
|
1872
|
+
runId,
|
|
1873
|
+
reason: "Stopped from Tencil",
|
|
1874
|
+
holdQueue: true
|
|
1875
|
+
});
|
|
1876
|
+
},
|
|
1877
|
+
createTracker: () => new V2ThreadTracker()
|
|
1878
|
+
};
|
|
1879
|
+
async function persist(socket, threadId, messageId, attachments) {
|
|
1880
|
+
if (attachments.length === 0) return [];
|
|
1881
|
+
return (await socket.request("assets.persistChatAttachments", {
|
|
1882
|
+
threadId,
|
|
1883
|
+
messageId,
|
|
1884
|
+
attachments: attachments.map((attachment) => ({
|
|
1885
|
+
type: "image",
|
|
1886
|
+
name: attachment.name,
|
|
1887
|
+
mimeType: attachment.mimeType,
|
|
1888
|
+
sizeBytes: decodedSize(attachment.dataUrl),
|
|
1889
|
+
dataUrl: attachment.dataUrl
|
|
1890
|
+
}))
|
|
1891
|
+
})).attachments;
|
|
1892
|
+
}
|
|
1893
|
+
const ACTIVE_RUN_STATUSES = /* @__PURE__ */ new Set([
|
|
1894
|
+
"preparing",
|
|
1895
|
+
"starting",
|
|
1896
|
+
"running",
|
|
1897
|
+
"waiting"
|
|
1898
|
+
]);
|
|
1899
|
+
var V2ThreadTracker = class {
|
|
1900
|
+
#runs = /* @__PURE__ */ new Map();
|
|
1901
|
+
#messages = /* @__PURE__ */ new Map();
|
|
1902
|
+
#lastStatusKey = "";
|
|
1903
|
+
apply(raw) {
|
|
1904
|
+
const item = raw;
|
|
1905
|
+
const changed = [];
|
|
1906
|
+
let gone = false;
|
|
1907
|
+
if (item.kind === "snapshot") {
|
|
1908
|
+
for (const run of item.projection.runs ?? []) this.#runs.set(run.id, run);
|
|
1909
|
+
for (const message of item.projection.messages ?? []) this.#upsertMessage(message, changed);
|
|
1910
|
+
for (const turnItem of item.projection.turnItems ?? []) this.#upsertTurnItem(turnItem, changed);
|
|
1911
|
+
} else if (item.kind === "event") {
|
|
1912
|
+
const { type, payload } = item.event;
|
|
1913
|
+
if (type === "run.created" || type === "run.updated") {
|
|
1914
|
+
const run = payload;
|
|
1915
|
+
this.#runs.set(run.id, run);
|
|
1916
|
+
} else if (type === "message.updated") this.#upsertMessage(payload, changed);
|
|
1917
|
+
else if (type === "turn-item.updated") this.#upsertTurnItem(payload, changed);
|
|
1918
|
+
else if (type === "thread.deleted") gone = true;
|
|
1919
|
+
}
|
|
1920
|
+
const update = { messages: changed };
|
|
1921
|
+
if (gone) update.gone = true;
|
|
1922
|
+
const status = this.status();
|
|
1923
|
+
const statusKey = `${status.status}:${status.detail ?? ""}`;
|
|
1924
|
+
if (statusKey !== this.#lastStatusKey) {
|
|
1925
|
+
this.#lastStatusKey = statusKey;
|
|
1926
|
+
update.status = status;
|
|
1927
|
+
}
|
|
1928
|
+
return update;
|
|
1929
|
+
}
|
|
1930
|
+
status() {
|
|
1931
|
+
const latest = this.#latestRun();
|
|
1932
|
+
if (!latest) return { status: "idle" };
|
|
1933
|
+
switch (latest.status) {
|
|
1934
|
+
case "preparing":
|
|
1935
|
+
case "queued":
|
|
1936
|
+
case "starting":
|
|
1937
|
+
case "running": return { status: "working" };
|
|
1938
|
+
case "waiting": return {
|
|
1939
|
+
status: "waiting",
|
|
1940
|
+
detail: "Waiting for approval in T3 Code"
|
|
1941
|
+
};
|
|
1942
|
+
case "failed": return {
|
|
1943
|
+
status: "error",
|
|
1944
|
+
detail: "Run failed"
|
|
1945
|
+
};
|
|
1946
|
+
case "interrupted":
|
|
1947
|
+
case "cancelled": return {
|
|
1948
|
+
status: "idle",
|
|
1949
|
+
detail: "Stopped"
|
|
1950
|
+
};
|
|
1951
|
+
default: return { status: "idle" };
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
activeTurnId() {
|
|
1955
|
+
let active;
|
|
1956
|
+
for (const run of this.#runs.values()) {
|
|
1957
|
+
if (!ACTIVE_RUN_STATUSES.has(run.status)) continue;
|
|
1958
|
+
if (!active || run.ordinal > active.ordinal) active = run;
|
|
1959
|
+
}
|
|
1960
|
+
return active?.id;
|
|
1961
|
+
}
|
|
1962
|
+
#latestRun() {
|
|
1963
|
+
let latest;
|
|
1964
|
+
for (const run of this.#runs.values()) if (!latest || run.ordinal > latest.ordinal) latest = run;
|
|
1965
|
+
return latest;
|
|
1966
|
+
}
|
|
1967
|
+
#upsertMessage(message, changed) {
|
|
1968
|
+
if (message.role === "system") return;
|
|
1969
|
+
this.#set({
|
|
1970
|
+
id: message.id,
|
|
1971
|
+
role: message.role,
|
|
1972
|
+
text: message.text,
|
|
1973
|
+
streaming: message.streaming,
|
|
1974
|
+
createdAt: message.createdAt
|
|
1975
|
+
}, changed);
|
|
1976
|
+
}
|
|
1977
|
+
/** Assistant text streams as turn items before (or instead of) a message update. */
|
|
1978
|
+
#upsertTurnItem(item, changed) {
|
|
1979
|
+
if (item.type !== "assistant_message" || !item.messageId) return;
|
|
1980
|
+
const existing = this.#messages.get(item.messageId);
|
|
1981
|
+
this.#set({
|
|
1982
|
+
id: item.messageId,
|
|
1983
|
+
role: "assistant",
|
|
1984
|
+
text: item.text ?? "",
|
|
1985
|
+
streaming: item.streaming ?? false,
|
|
1986
|
+
createdAt: existing?.createdAt ?? item.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1987
|
+
}, changed);
|
|
1988
|
+
}
|
|
1989
|
+
#set(next, changed) {
|
|
1990
|
+
const previous = this.#messages.get(next.id);
|
|
1991
|
+
if (previous && previous.text === next.text && previous.streaming === next.streaming) return;
|
|
1992
|
+
this.#messages.set(next.id, next);
|
|
1993
|
+
const index = changed.findIndex((message) => message.id === next.id);
|
|
1994
|
+
if (index === -1) changed.push(next);
|
|
1995
|
+
else changed[index] = next;
|
|
1996
|
+
}
|
|
1997
|
+
};
|
|
1998
|
+
//#endregion
|
|
1999
|
+
//#region ../provider-t3code/src/rpc-socket.ts
|
|
2000
|
+
var RpcError = class extends Error {
|
|
2001
|
+
tag;
|
|
2002
|
+
details;
|
|
2003
|
+
constructor(message, tag, details) {
|
|
2004
|
+
super(message);
|
|
2005
|
+
this.tag = tag;
|
|
2006
|
+
this.details = details;
|
|
2007
|
+
this.name = "RpcError";
|
|
2008
|
+
}
|
|
2009
|
+
};
|
|
2010
|
+
const PING_INTERVAL_MS = 15e3;
|
|
2011
|
+
var RpcSocket = class RpcSocket {
|
|
2012
|
+
#ws;
|
|
2013
|
+
#nextId = 1;
|
|
2014
|
+
#pending = /* @__PURE__ */ new Map();
|
|
2015
|
+
#ping;
|
|
2016
|
+
#closeListeners = /* @__PURE__ */ new Set();
|
|
2017
|
+
constructor(ws) {
|
|
2018
|
+
this.#ws = ws;
|
|
2019
|
+
ws.addEventListener("message", (event) => this.#onFrame(String(event.data)));
|
|
2020
|
+
ws.addEventListener("close", (event) => this.#onClose(event.reason || `code ${event.code}`));
|
|
2021
|
+
this.#ping = setInterval(() => this.#send({ _tag: "Ping" }), PING_INTERVAL_MS);
|
|
2022
|
+
}
|
|
2023
|
+
/** Default for `request` when no timeout is passed. */
|
|
2024
|
+
requestTimeoutMs = 3e4;
|
|
2025
|
+
static open(url, timeoutMs = 1e4) {
|
|
2026
|
+
return new Promise((resolve, reject) => {
|
|
2027
|
+
const ws = new WebSocket(url);
|
|
2028
|
+
const timer = setTimeout(() => {
|
|
2029
|
+
ws.close();
|
|
2030
|
+
reject(new RpcError(`Timed out connecting to ${redactTicket(url)}`));
|
|
2031
|
+
}, timeoutMs);
|
|
2032
|
+
ws.addEventListener("open", () => {
|
|
2033
|
+
clearTimeout(timer);
|
|
2034
|
+
resolve(new RpcSocket(ws));
|
|
2035
|
+
});
|
|
2036
|
+
ws.addEventListener("error", () => {
|
|
2037
|
+
clearTimeout(timer);
|
|
2038
|
+
reject(new RpcError(`Could not connect to ${redactTicket(url)}`));
|
|
2039
|
+
});
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
get open() {
|
|
2043
|
+
return this.#ws.readyState === WebSocket.OPEN;
|
|
2044
|
+
}
|
|
2045
|
+
onClose(listener) {
|
|
2046
|
+
this.#closeListeners.add(listener);
|
|
2047
|
+
return () => this.#closeListeners.delete(listener);
|
|
2048
|
+
}
|
|
2049
|
+
/** Unary request; rejects after `timeoutMs` so a stalled server can't hang callers. */
|
|
2050
|
+
request(tag, payload, timeoutMs = this.requestTimeoutMs) {
|
|
2051
|
+
return new Promise((resolve, reject) => {
|
|
2052
|
+
let timer;
|
|
2053
|
+
const id = this.#start(tag, payload, {
|
|
2054
|
+
resolve: (value) => {
|
|
2055
|
+
clearTimeout(timer);
|
|
2056
|
+
resolve(value);
|
|
2057
|
+
},
|
|
2058
|
+
reject: (error) => {
|
|
2059
|
+
clearTimeout(timer);
|
|
2060
|
+
reject(error);
|
|
2061
|
+
}
|
|
2062
|
+
});
|
|
2063
|
+
if (!id) {
|
|
2064
|
+
reject(new RpcError("Socket is closed"));
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
timer = setTimeout(() => {
|
|
2068
|
+
if (!this.#pending.delete(id)) return;
|
|
2069
|
+
this.#send({
|
|
2070
|
+
_tag: "Interrupt",
|
|
2071
|
+
requestId: id
|
|
2072
|
+
});
|
|
2073
|
+
reject(new RpcError(`${tag} timed out after ${timeoutMs / 1e3}s`));
|
|
2074
|
+
}, timeoutMs);
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
/**
|
|
2078
|
+
* Open a server stream. `onItem` receives every value; the returned promise
|
|
2079
|
+
* settles when the stream ends. Call the returned `cancel` to unsubscribe.
|
|
2080
|
+
*/
|
|
2081
|
+
stream(tag, payload, onItem) {
|
|
2082
|
+
let id;
|
|
2083
|
+
return {
|
|
2084
|
+
done: new Promise((resolve, reject) => {
|
|
2085
|
+
id = this.#start(tag, payload, {
|
|
2086
|
+
onChunk: onItem,
|
|
2087
|
+
resolve: () => resolve(),
|
|
2088
|
+
reject
|
|
2089
|
+
});
|
|
2090
|
+
if (!id) reject(new RpcError("Socket is closed"));
|
|
2091
|
+
}),
|
|
2092
|
+
cancel: () => {
|
|
2093
|
+
if (!id || !this.#pending.has(id)) return;
|
|
2094
|
+
this.#pending.delete(id);
|
|
2095
|
+
this.#send({
|
|
2096
|
+
_tag: "Interrupt",
|
|
2097
|
+
requestId: id
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
close() {
|
|
2103
|
+
this.#ws.close(1e3, "client closed");
|
|
2104
|
+
}
|
|
2105
|
+
#start(tag, payload, pending) {
|
|
2106
|
+
if (!this.open) return void 0;
|
|
2107
|
+
const id = String(this.#nextId++);
|
|
2108
|
+
this.#pending.set(id, pending);
|
|
2109
|
+
this.#send({
|
|
2110
|
+
_tag: "Request",
|
|
2111
|
+
id,
|
|
2112
|
+
tag,
|
|
2113
|
+
payload,
|
|
2114
|
+
headers: []
|
|
2115
|
+
});
|
|
2116
|
+
return id;
|
|
2117
|
+
}
|
|
2118
|
+
#send(frame) {
|
|
2119
|
+
if (this.open) this.#ws.send(JSON.stringify(frame));
|
|
2120
|
+
}
|
|
2121
|
+
#onFrame(raw) {
|
|
2122
|
+
let parsed;
|
|
2123
|
+
try {
|
|
2124
|
+
parsed = JSON.parse(raw);
|
|
2125
|
+
} catch {
|
|
2126
|
+
return;
|
|
2127
|
+
}
|
|
2128
|
+
for (const frame of Array.isArray(parsed) ? parsed : [parsed]) this.#handle(frame);
|
|
2129
|
+
}
|
|
2130
|
+
#handle(frame) {
|
|
2131
|
+
switch (frame._tag) {
|
|
2132
|
+
case "Chunk": {
|
|
2133
|
+
const pending = this.#pending.get(frame.requestId);
|
|
2134
|
+
this.#send({
|
|
2135
|
+
_tag: "Ack",
|
|
2136
|
+
requestId: frame.requestId
|
|
2137
|
+
});
|
|
2138
|
+
if (pending?.onChunk) for (const value of frame.values) pending.onChunk(value);
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
2141
|
+
case "Exit": {
|
|
2142
|
+
const pending = this.#pending.get(frame.requestId);
|
|
2143
|
+
if (!pending) return;
|
|
2144
|
+
this.#pending.delete(frame.requestId);
|
|
2145
|
+
if (frame.exit._tag === "Success") pending.resolve(frame.exit.value);
|
|
2146
|
+
else pending.reject(errorFromCause(frame.exit.cause));
|
|
2147
|
+
return;
|
|
2148
|
+
}
|
|
2149
|
+
case "Defect":
|
|
2150
|
+
case "ClientProtocolError": {
|
|
2151
|
+
const error = new RpcError(`Server protocol error: ${describe("defect" in frame ? frame.defect : frame.error)}`);
|
|
2152
|
+
for (const pending of this.#pending.values()) pending.reject(error);
|
|
2153
|
+
this.#pending.clear();
|
|
2154
|
+
return;
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
#onClose(reason) {
|
|
2159
|
+
clearInterval(this.#ping);
|
|
2160
|
+
const error = new RpcError(`Connection closed (${reason})`);
|
|
2161
|
+
for (const pending of this.#pending.values()) pending.reject(error);
|
|
2162
|
+
this.#pending.clear();
|
|
2163
|
+
for (const listener of this.#closeListeners) listener(reason);
|
|
2164
|
+
}
|
|
2165
|
+
};
|
|
2166
|
+
function errorFromCause(cause) {
|
|
2167
|
+
const fail = cause.find((entry) => entry._tag === "Fail");
|
|
2168
|
+
if (fail && fail._tag === "Fail") {
|
|
2169
|
+
const error = fail.error;
|
|
2170
|
+
return new RpcError(error?.message ?? error?._tag ?? describe(fail.error), error?._tag, fail.error);
|
|
2171
|
+
}
|
|
2172
|
+
const die = cause.find((entry) => entry._tag === "Die");
|
|
2173
|
+
if (die && die._tag === "Die") return new RpcError(`Server defect: ${describe(die.defect)}`);
|
|
2174
|
+
return new RpcError("Request interrupted");
|
|
2175
|
+
}
|
|
2176
|
+
function describe(value) {
|
|
2177
|
+
if (typeof value === "string") return value;
|
|
2178
|
+
try {
|
|
2179
|
+
return JSON.stringify(value);
|
|
2180
|
+
} catch {
|
|
2181
|
+
return String(value);
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
function redactTicket(url) {
|
|
2185
|
+
return url.replace(/wsTicket=[^&]+/, "wsTicket=…");
|
|
2186
|
+
}
|
|
2187
|
+
//#endregion
|
|
2188
|
+
//#region ../provider-t3code/src/t3code-provider.ts
|
|
2189
|
+
const DEFAULT_TIMEOUTS = {
|
|
2190
|
+
httpMs: 8e3,
|
|
2191
|
+
rpcMs: 3e4,
|
|
2192
|
+
retryMinMs: 1e3,
|
|
2193
|
+
retryMaxMs: 15e3
|
|
2194
|
+
};
|
|
2195
|
+
var T3CodeProvider = class {
|
|
2196
|
+
id = "t3code";
|
|
2197
|
+
label = "T3 Code";
|
|
2198
|
+
#options;
|
|
2199
|
+
#credentials;
|
|
2200
|
+
#baseUrl;
|
|
2201
|
+
#info = {
|
|
2202
|
+
id: "t3code",
|
|
2203
|
+
label: "T3 Code",
|
|
2204
|
+
state: "connecting",
|
|
2205
|
+
canPair: true
|
|
2206
|
+
};
|
|
2207
|
+
#infoListeners = /* @__PURE__ */ new Set();
|
|
2208
|
+
#connection;
|
|
2209
|
+
#watchers = /* @__PURE__ */ new Map();
|
|
2210
|
+
#timeouts;
|
|
2211
|
+
#retryDelay;
|
|
2212
|
+
#retryTimer;
|
|
2213
|
+
#disposed = false;
|
|
2214
|
+
#connecting = false;
|
|
2215
|
+
/** Set once a project was resolved; later reconnects never re-create a deleted project. */
|
|
2216
|
+
#hadProject = false;
|
|
2217
|
+
/** Auto-pairing runs once per server; after that the user pairs explicitly. */
|
|
2218
|
+
#autoPaired = /* @__PURE__ */ new Set();
|
|
2219
|
+
constructor(options) {
|
|
2220
|
+
this.#options = options;
|
|
2221
|
+
this.#timeouts = {
|
|
2222
|
+
...DEFAULT_TIMEOUTS,
|
|
2223
|
+
...options.timeouts
|
|
2224
|
+
};
|
|
2225
|
+
this.#retryDelay = this.#timeouts.retryMinMs;
|
|
2226
|
+
this.#baseUrl = normalizeBaseUrl(options.baseUrl ?? "http://127.0.0.1:3773");
|
|
2227
|
+
this.#credentials = options.credentials ?? new CredentialStore();
|
|
2228
|
+
}
|
|
2229
|
+
async start() {
|
|
2230
|
+
await this.#connect();
|
|
2231
|
+
}
|
|
2232
|
+
/**
|
|
2233
|
+
* Pair with the local T3 Code: mint a pairing code, exchange it for a token
|
|
2234
|
+
* and reconnect. Used automatically on first run and by the overlay's Pair button.
|
|
2235
|
+
*/
|
|
2236
|
+
async pair() {
|
|
2237
|
+
if (!this.#options.baseUrl) {
|
|
2238
|
+
const paired = await this.#credentials.lastBaseUrl();
|
|
2239
|
+
if (paired) this.#baseUrl = normalizeBaseUrl(paired);
|
|
2240
|
+
}
|
|
2241
|
+
this.#setInfo({
|
|
2242
|
+
state: "connecting",
|
|
2243
|
+
detail: "Pairing with T3 Code…"
|
|
2244
|
+
});
|
|
2245
|
+
const code = await (this.#options.createPairingCode ?? createLocalPairingCode)(this.#baseUrl).catch(() => void 0);
|
|
2246
|
+
if (!code) {
|
|
2247
|
+
this.#setInfo({
|
|
2248
|
+
state: "unauthorized",
|
|
2249
|
+
detail: "Couldn't pair automatically. Run `npx tencil connect` with a pairing link from T3 Code."
|
|
2250
|
+
});
|
|
2251
|
+
this.#scheduleReconnect();
|
|
2252
|
+
return;
|
|
2253
|
+
}
|
|
2254
|
+
try {
|
|
2255
|
+
const credential = await exchangePairingCredential({
|
|
2256
|
+
baseUrl: this.#baseUrl,
|
|
2257
|
+
credential: code
|
|
2258
|
+
});
|
|
2259
|
+
await this.#credentials.set(this.#baseUrl, credential);
|
|
2260
|
+
this.#log(`Paired with T3 Code at ${this.#baseUrl}`);
|
|
2261
|
+
} catch (error) {
|
|
2262
|
+
this.#setInfo({
|
|
2263
|
+
state: "unauthorized",
|
|
2264
|
+
detail: errorMessage(error)
|
|
2265
|
+
});
|
|
2266
|
+
this.#scheduleReconnect();
|
|
2267
|
+
return;
|
|
2268
|
+
}
|
|
2269
|
+
clearTimeout(this.#retryTimer);
|
|
2270
|
+
this.#retryDelay = this.#timeouts.retryMinMs;
|
|
2271
|
+
await this.#connect();
|
|
2272
|
+
}
|
|
2273
|
+
info() {
|
|
2274
|
+
return this.#info;
|
|
2275
|
+
}
|
|
2276
|
+
onInfoChange(listener) {
|
|
2277
|
+
this.#infoListeners.add(listener);
|
|
2278
|
+
return () => this.#infoListeners.delete(listener);
|
|
2279
|
+
}
|
|
2280
|
+
async listThreads() {
|
|
2281
|
+
const connection = this.#requireConnection();
|
|
2282
|
+
const [shell, drivers, project] = await Promise.all([
|
|
2283
|
+
this.#fetchJson("/api/orchestration/shell", connection.token),
|
|
2284
|
+
this.#drivers(connection),
|
|
2285
|
+
this.#projectPresentation(connection)
|
|
2286
|
+
]);
|
|
2287
|
+
return {
|
|
2288
|
+
project,
|
|
2289
|
+
threads: shell.threads.filter((thread) => thread.projectId === connection.project.id && !thread.archivedAt).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).map((thread) => {
|
|
2290
|
+
const pullRequest = thread.linkedPullRequest ?? thread.branchPullRequest;
|
|
2291
|
+
const instance = thread.modelSelection?.instanceId ?? thread.modelSelection?.provider;
|
|
2292
|
+
return {
|
|
2293
|
+
id: thread.id,
|
|
2294
|
+
title: thread.title,
|
|
2295
|
+
status: summaryStatus(thread),
|
|
2296
|
+
updatedAt: thread.updatedAt,
|
|
2297
|
+
url: this.#threadUrl(connection, thread.id),
|
|
2298
|
+
...thread.branch ? { branch: thread.branch } : {},
|
|
2299
|
+
...pullRequest ? { pullRequest: {
|
|
2300
|
+
number: pullRequest.number,
|
|
2301
|
+
url: pullRequest.url
|
|
2302
|
+
} } : {},
|
|
2303
|
+
...thread.backgroundLiveness ? { background: thread.backgroundLiveness } : {},
|
|
2304
|
+
...instance ? { agent: drivers.get(instance) ?? instance } : {}
|
|
2305
|
+
};
|
|
2306
|
+
})
|
|
2307
|
+
};
|
|
2308
|
+
}
|
|
2309
|
+
async #drivers(connection) {
|
|
2310
|
+
if (connection.drivers) return connection.drivers;
|
|
2311
|
+
const config = await connection.socket.request("server.getConfig", {}).catch(() => ({ providers: [] }));
|
|
2312
|
+
connection.drivers = new Map(config.providers.map((provider) => [provider.instanceId, provider.driver ?? provider.instanceId]));
|
|
2313
|
+
return connection.drivers;
|
|
2314
|
+
}
|
|
2315
|
+
/** Name like `owner/repo` and the project icon, matching T3 Code's sidebar. */
|
|
2316
|
+
async #projectPresentation(connection) {
|
|
2317
|
+
const { project } = connection;
|
|
2318
|
+
const identity = project.repositoryIdentity;
|
|
2319
|
+
const name = identity?.owner && identity.name ? `${identity.owner}/${identity.name}` : identity?.displayName ?? project.title;
|
|
2320
|
+
const override = project.projectIcon;
|
|
2321
|
+
if (override && override.kind === "emoji" && "emoji" in override) return {
|
|
2322
|
+
name,
|
|
2323
|
+
emoji: override.emoji
|
|
2324
|
+
};
|
|
2325
|
+
if (!connection.icon || connection.icon.expiresAt - 3e4 < Date.now()) {
|
|
2326
|
+
const signed = await connection.socket.request("assets.createUrl", { resource: {
|
|
2327
|
+
_tag: "project-favicon",
|
|
2328
|
+
cwd: project.workspaceRoot
|
|
2329
|
+
} }).catch(() => null);
|
|
2330
|
+
if (signed) {
|
|
2331
|
+
const expiresAt = signed.expiresAt < 0xe8d4a51000 ? signed.expiresAt * 1e3 : signed.expiresAt;
|
|
2332
|
+
connection.icon = {
|
|
2333
|
+
url: new URL(signed.relativeUrl, this.#baseUrl).toString(),
|
|
2334
|
+
expiresAt
|
|
2335
|
+
};
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
return connection.icon ? {
|
|
2339
|
+
name,
|
|
2340
|
+
iconUrl: connection.icon.url
|
|
2341
|
+
} : { name };
|
|
2342
|
+
}
|
|
2343
|
+
threadUrl(providerThreadId) {
|
|
2344
|
+
return this.#connection ? this.#threadUrl(this.#connection, providerThreadId) : void 0;
|
|
2345
|
+
}
|
|
2346
|
+
async createThread(input) {
|
|
2347
|
+
const connection = this.#requireConnection();
|
|
2348
|
+
const threadId = randomUUID();
|
|
2349
|
+
await connection.protocol.startThread(connection.socket, {
|
|
2350
|
+
threadId,
|
|
2351
|
+
projectId: connection.project.id,
|
|
2352
|
+
title: input.title,
|
|
2353
|
+
text: input.text,
|
|
2354
|
+
attachments: input.attachments,
|
|
2355
|
+
modelSelection: connection.modelSelection,
|
|
2356
|
+
runtimeMode: this.#runtimeMode(),
|
|
2357
|
+
interactionMode: this.#options.interactionMode ?? "default"
|
|
2358
|
+
});
|
|
2359
|
+
return {
|
|
2360
|
+
providerThreadId: threadId,
|
|
2361
|
+
url: this.#threadUrl(connection, threadId)
|
|
2362
|
+
};
|
|
2363
|
+
}
|
|
2364
|
+
async sendMessage(input) {
|
|
2365
|
+
const connection = this.#requireConnection();
|
|
2366
|
+
const tracker = this.#watchers.get(input.providerThreadId)?.tracker;
|
|
2367
|
+
await connection.protocol.sendMessage(connection.socket, {
|
|
2368
|
+
threadId: input.providerThreadId,
|
|
2369
|
+
text: input.text,
|
|
2370
|
+
attachments: input.attachments,
|
|
2371
|
+
busy: tracker?.status().status === "working",
|
|
2372
|
+
runtimeMode: this.#runtimeMode(),
|
|
2373
|
+
interactionMode: this.#options.interactionMode ?? "default"
|
|
2374
|
+
});
|
|
2375
|
+
}
|
|
2376
|
+
async interrupt(providerThreadId) {
|
|
2377
|
+
const connection = this.#requireConnection();
|
|
2378
|
+
const turnId = this.#watchers.get(providerThreadId)?.tracker.activeTurnId();
|
|
2379
|
+
if (!turnId) return;
|
|
2380
|
+
await connection.protocol.interrupt(connection.socket, providerThreadId, turnId);
|
|
2381
|
+
}
|
|
2382
|
+
watch(providerThreadId, sink) {
|
|
2383
|
+
this.#watchers.get(providerThreadId)?.cancel?.();
|
|
2384
|
+
const watcher = {
|
|
2385
|
+
sink,
|
|
2386
|
+
tracker: (this.#connection?.protocol ?? v1).createTracker()
|
|
2387
|
+
};
|
|
2388
|
+
this.#watchers.set(providerThreadId, watcher);
|
|
2389
|
+
if (this.#connection) this.#subscribe(this.#connection, providerThreadId, watcher);
|
|
2390
|
+
return () => {
|
|
2391
|
+
watcher.cancel?.();
|
|
2392
|
+
if (this.#watchers.get(providerThreadId) === watcher) this.#watchers.delete(providerThreadId);
|
|
2393
|
+
};
|
|
2394
|
+
}
|
|
2395
|
+
async dispose() {
|
|
2396
|
+
this.#disposed = true;
|
|
2397
|
+
clearTimeout(this.#retryTimer);
|
|
2398
|
+
for (const watcher of this.#watchers.values()) watcher.cancel?.();
|
|
2399
|
+
this.#watchers.clear();
|
|
2400
|
+
this.#connection?.socket.close();
|
|
2401
|
+
this.#connection = void 0;
|
|
2402
|
+
}
|
|
2403
|
+
async #connect() {
|
|
2404
|
+
if (this.#disposed || this.#connecting) return;
|
|
2405
|
+
this.#connecting = true;
|
|
2406
|
+
let unauthorized = false;
|
|
2407
|
+
try {
|
|
2408
|
+
const connection = await this.#establish();
|
|
2409
|
+
this.#connection = connection;
|
|
2410
|
+
this.#retryDelay = this.#timeouts.retryMinMs;
|
|
2411
|
+
this.#setInfo({
|
|
2412
|
+
state: "ready",
|
|
2413
|
+
target: connection.project.title
|
|
2414
|
+
});
|
|
2415
|
+
this.#log(`Connected to T3 Code at ${this.#baseUrl} · project "${connection.project.title}" · ${connection.modelSelection.instanceId}/${connection.modelSelection.model} · protocol v${connection.protocol.version}`);
|
|
2416
|
+
for (const [threadId, watcher] of this.#watchers) this.#subscribe(connection, threadId, watcher);
|
|
2417
|
+
} catch (error) {
|
|
2418
|
+
unauthorized = error instanceof UnauthorizedError;
|
|
2419
|
+
if (unauthorized) this.#setInfo({
|
|
2420
|
+
state: "unauthorized",
|
|
2421
|
+
detail: error.message
|
|
2422
|
+
});
|
|
2423
|
+
else this.#setInfo({
|
|
2424
|
+
state: "unavailable",
|
|
2425
|
+
detail: errorMessage(error)
|
|
2426
|
+
});
|
|
2427
|
+
} finally {
|
|
2428
|
+
this.#connecting = false;
|
|
2429
|
+
}
|
|
2430
|
+
if (this.#connection || this.#disposed) return;
|
|
2431
|
+
if (unauthorized && (this.#options.autoPair ?? true) && !this.#autoPaired.has(this.#baseUrl)) {
|
|
2432
|
+
this.#autoPaired.add(this.#baseUrl);
|
|
2433
|
+
await this.pair();
|
|
2434
|
+
return;
|
|
2435
|
+
}
|
|
2436
|
+
this.#scheduleReconnect();
|
|
2437
|
+
}
|
|
2438
|
+
async #establish() {
|
|
2439
|
+
if (!this.#options.baseUrl) {
|
|
2440
|
+
const paired = await this.#credentials.lastBaseUrl();
|
|
2441
|
+
if (paired) this.#baseUrl = normalizeBaseUrl(paired);
|
|
2442
|
+
}
|
|
2443
|
+
const environment = await this.#fetchJson("/.well-known/t3/environment", void 0, `T3 Code isn't running at ${this.#baseUrl}. Open T3 Code and Tencil connects on its own.`);
|
|
2444
|
+
const protocol = environment.orchestrationProtocolVersion === 2 ? v2 : v1;
|
|
2445
|
+
const token = this.#options.token ?? (await this.#credentials.get(this.#baseUrl))?.token;
|
|
2446
|
+
if (!token) throw new UnauthorizedError("Not paired with T3 Code yet. Press Pair, or run `npx tencil connect`.");
|
|
2447
|
+
const ticket = await requestWebSocketTicket(this.#baseUrl, token, this.#timeouts.httpMs);
|
|
2448
|
+
const wsUrl = new URL("/ws", this.#baseUrl);
|
|
2449
|
+
wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
|
|
2450
|
+
if (protocol.version === 2) wsUrl.searchParams.set("orchestrationProtocol", "2");
|
|
2451
|
+
wsUrl.searchParams.set("wsTicket", ticket);
|
|
2452
|
+
const socket = await RpcSocket.open(wsUrl.toString());
|
|
2453
|
+
socket.requestTimeoutMs = this.#timeouts.rpcMs;
|
|
2454
|
+
try {
|
|
2455
|
+
const project = await this.#resolveProject(socket, protocol, token);
|
|
2456
|
+
const modelSelection = this.#options.modelSelection ?? project.defaultModelSelection ?? await this.#defaultModelSelection(socket);
|
|
2457
|
+
socket.onClose((reason) => {
|
|
2458
|
+
if (this.#connection?.socket !== socket) return;
|
|
2459
|
+
this.#connection = void 0;
|
|
2460
|
+
for (const watcher of this.#watchers.values()) watcher.cancel = void 0;
|
|
2461
|
+
this.#setInfo({
|
|
2462
|
+
state: "connecting",
|
|
2463
|
+
detail: `Reconnecting (${reason})`
|
|
2464
|
+
});
|
|
2465
|
+
this.#scheduleReconnect();
|
|
2466
|
+
});
|
|
2467
|
+
return {
|
|
2468
|
+
token,
|
|
2469
|
+
socket,
|
|
2470
|
+
protocol,
|
|
2471
|
+
environmentId: environment.environmentId,
|
|
2472
|
+
project,
|
|
2473
|
+
modelSelection
|
|
2474
|
+
};
|
|
2475
|
+
} catch (error) {
|
|
2476
|
+
socket.close();
|
|
2477
|
+
throw error;
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
#scheduleReconnect() {
|
|
2481
|
+
if (this.#disposed) return;
|
|
2482
|
+
clearTimeout(this.#retryTimer);
|
|
2483
|
+
this.#retryTimer = setTimeout(() => void this.#connect(), this.#retryDelay);
|
|
2484
|
+
this.#retryDelay = Math.min(this.#retryDelay * 2, this.#timeouts.retryMaxMs);
|
|
2485
|
+
}
|
|
2486
|
+
async #resolveProject(socket, protocol, token) {
|
|
2487
|
+
const root = await realpath(this.#options.projectRoot).catch(() => this.#options.projectRoot);
|
|
2488
|
+
const shell = await this.#fetchJson("/api/orchestration/shell", token);
|
|
2489
|
+
const repository = await repositoryRoot(root);
|
|
2490
|
+
let match;
|
|
2491
|
+
for (const project of shell.projects) {
|
|
2492
|
+
const projectRoot = await realpath(project.workspaceRoot).catch(() => project.workspaceRoot);
|
|
2493
|
+
if (isInside(root, projectRoot) && (!repository || isInside(projectRoot, repository)) && (!match || projectRoot.length > match.workspaceRoot.length)) match = {
|
|
2494
|
+
...project,
|
|
2495
|
+
workspaceRoot: projectRoot
|
|
2496
|
+
};
|
|
2497
|
+
}
|
|
2498
|
+
if (match) {
|
|
2499
|
+
this.#hadProject = true;
|
|
2500
|
+
return match;
|
|
2501
|
+
}
|
|
2502
|
+
if (!this.#options.createProjectIfMissing || this.#hadProject) throw new Error(`No T3 Code project for ${root}. Add the folder in T3 Code first.`);
|
|
2503
|
+
const workspaceRoot = repository ?? root;
|
|
2504
|
+
const project = {
|
|
2505
|
+
id: randomUUID(),
|
|
2506
|
+
title: basename(workspaceRoot),
|
|
2507
|
+
workspaceRoot,
|
|
2508
|
+
defaultModelSelection: null
|
|
2509
|
+
};
|
|
2510
|
+
await protocol.createProject(socket, {
|
|
2511
|
+
projectId: project.id,
|
|
2512
|
+
title: project.title,
|
|
2513
|
+
workspaceRoot: project.workspaceRoot
|
|
2514
|
+
});
|
|
2515
|
+
this.#log(`Added ${workspaceRoot} to T3 Code as project "${project.title}"`);
|
|
2516
|
+
this.#hadProject = true;
|
|
2517
|
+
return project;
|
|
2518
|
+
}
|
|
2519
|
+
async #defaultModelSelection(socket) {
|
|
2520
|
+
const usable = (await socket.request("server.getConfig", {})).providers.filter((provider) => provider.enabled && provider.installed && provider.status !== "error");
|
|
2521
|
+
const provider = usable.find((p) => p.status === "ready") ?? usable[0];
|
|
2522
|
+
const model = provider?.models.find((m) => m.isDefault) ?? provider?.models[0];
|
|
2523
|
+
if (!provider || !model) throw new Error("T3 Code has no usable provider. Set one up in T3 Code → Settings → Providers.");
|
|
2524
|
+
return {
|
|
2525
|
+
instanceId: provider.instanceId,
|
|
2526
|
+
model: model.slug
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
#subscribe(connection, threadId, watcher) {
|
|
2530
|
+
watcher.cancel?.();
|
|
2531
|
+
watcher.tracker = connection.protocol.createTracker();
|
|
2532
|
+
const stream = connection.socket.stream("orchestration.subscribeThread", { threadId }, (item) => {
|
|
2533
|
+
const update = watcher.tracker.apply(item);
|
|
2534
|
+
for (const message of update.messages) watcher.sink.message(message);
|
|
2535
|
+
if (update.status) watcher.sink.status(update.status.status, update.status.detail);
|
|
2536
|
+
if (update.gone) watcher.sink.gone();
|
|
2537
|
+
});
|
|
2538
|
+
watcher.cancel = stream.cancel;
|
|
2539
|
+
stream.done.catch((error) => {
|
|
2540
|
+
if (error instanceof RpcError && /not.?found/i.test(`${error.tag} ${error.message}`)) watcher.sink.gone();
|
|
2541
|
+
});
|
|
2542
|
+
}
|
|
2543
|
+
#threadUrl(connection, threadId) {
|
|
2544
|
+
return `${this.#baseUrl}/${connection.environmentId}/${threadId}`;
|
|
2545
|
+
}
|
|
2546
|
+
#runtimeMode() {
|
|
2547
|
+
return this.#options.runtimeMode ?? "full-access";
|
|
2548
|
+
}
|
|
2549
|
+
#requireConnection() {
|
|
2550
|
+
if (!this.#connection) throw new Error(this.#info.detail ?? "T3 Code is not connected yet");
|
|
2551
|
+
return this.#connection;
|
|
2552
|
+
}
|
|
2553
|
+
async #fetchJson(path, token, unreachableMessage) {
|
|
2554
|
+
let response;
|
|
2555
|
+
try {
|
|
2556
|
+
response = await fetch(new URL(path, this.#baseUrl), {
|
|
2557
|
+
signal: AbortSignal.timeout(this.#timeouts.httpMs),
|
|
2558
|
+
headers: {
|
|
2559
|
+
"x-t3-orchestration-protocol": "2",
|
|
2560
|
+
...token ? { authorization: `Bearer ${token}` } : {}
|
|
2561
|
+
}
|
|
2562
|
+
});
|
|
2563
|
+
} catch {
|
|
2564
|
+
throw new Error(unreachableMessage ?? `Request to ${path} failed`);
|
|
2565
|
+
}
|
|
2566
|
+
if (response.status === 401 || response.status === 403) throw new UnauthorizedError();
|
|
2567
|
+
if (!response.ok) throw new Error(`${path} returned ${response.status}`);
|
|
2568
|
+
return await response.json();
|
|
2569
|
+
}
|
|
2570
|
+
#setInfo(next) {
|
|
2571
|
+
const info = {
|
|
2572
|
+
id: this.id,
|
|
2573
|
+
label: this.label,
|
|
2574
|
+
canPair: true,
|
|
2575
|
+
...next
|
|
2576
|
+
};
|
|
2577
|
+
if (info.state === this.#info.state && info.detail === this.#info.detail && info.target === this.#info.target) return;
|
|
2578
|
+
this.#info = info;
|
|
2579
|
+
for (const listener of this.#infoListeners) listener(info);
|
|
2580
|
+
}
|
|
2581
|
+
#log(message) {
|
|
2582
|
+
this.#options.log?.(message);
|
|
2583
|
+
}
|
|
2584
|
+
};
|
|
2585
|
+
function summaryStatus(thread) {
|
|
2586
|
+
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return "waiting";
|
|
2587
|
+
const session = thread.session?.status ?? thread.status;
|
|
2588
|
+
if (session === "running" || session === "starting") return "working";
|
|
2589
|
+
if (thread.latestTurn?.state === "running") return "working";
|
|
2590
|
+
if (session === "error" || thread.latestTurn?.state === "error") return "error";
|
|
2591
|
+
return "idle";
|
|
2592
|
+
}
|
|
2593
|
+
/** The nearest folder at or above `dir` with a `.git` entry, if any. */
|
|
2594
|
+
async function repositoryRoot(dir) {
|
|
2595
|
+
for (let current = dir;; current = dirname(current)) {
|
|
2596
|
+
if (await exists(join(current, ".git"))) return current;
|
|
2597
|
+
if (dirname(current) === current) return void 0;
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
const exists = (path) => access(path).then(() => true, () => false);
|
|
2601
|
+
/** Whether `path` is `parent` or inside it, on any platform's separators. */
|
|
2602
|
+
function isInside(path, parent) {
|
|
2603
|
+
const rel = relative(parent, path);
|
|
2604
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
2605
|
+
}
|
|
2606
|
+
function errorMessage(error) {
|
|
2607
|
+
return error instanceof Error ? error.message : String(error);
|
|
2608
|
+
}
|
|
2609
|
+
//#endregion
|
|
2610
|
+
//#region src/version.ts
|
|
2611
|
+
const VERSION = "0.3.1";
|
|
2612
|
+
//#endregion
|
|
2613
|
+
//#region src/daemon/thread-store.ts
|
|
2614
|
+
const StoreFile = z.object({
|
|
2615
|
+
version: z.literal(1),
|
|
2616
|
+
/** Project the pins belong to; informational, the file name is the key. */
|
|
2617
|
+
root: z.string().optional(),
|
|
2618
|
+
threads: z.array(Thread)
|
|
2619
|
+
});
|
|
2620
|
+
/** Where Tencil keeps per-machine state, shared by every project. */
|
|
2621
|
+
function defaultDataDir() {
|
|
2622
|
+
return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "tencil");
|
|
2623
|
+
}
|
|
2624
|
+
/**
|
|
2625
|
+
* One file per project under the global data dir, named after the folder plus
|
|
2626
|
+
* a hash of its path: readable when browsing, unique per checkout, and never
|
|
2627
|
+
* shared between two bridges.
|
|
2628
|
+
*/
|
|
2629
|
+
function projectStorePath(projectRoot, dataDir = defaultDataDir()) {
|
|
2630
|
+
const root = resolve(projectRoot);
|
|
2631
|
+
const hash = createHash("sha256").update(root).digest("hex").slice(0, 10);
|
|
2632
|
+
const slug = basename(root).replace(/[^a-z0-9._-]+/gi, "-").slice(0, 40) || "project";
|
|
2633
|
+
return join(dataDir, "projects", `${slug}-${hash}.json`);
|
|
2634
|
+
}
|
|
2635
|
+
/**
|
|
2636
|
+
* Pins for one project, persisted outside the repo so they survive bridge
|
|
2637
|
+
* restarts without leaving files in the project. Writes are debounced and atomic.
|
|
2638
|
+
*/
|
|
2639
|
+
var ThreadStore = class {
|
|
2640
|
+
path;
|
|
2641
|
+
#root;
|
|
2642
|
+
#threads = /* @__PURE__ */ new Map();
|
|
2643
|
+
#writeTimer;
|
|
2644
|
+
#writing = Promise.resolve();
|
|
2645
|
+
constructor(projectRoot, dataDir) {
|
|
2646
|
+
this.#root = resolve(projectRoot);
|
|
2647
|
+
this.path = projectStorePath(this.#root, dataDir);
|
|
2648
|
+
}
|
|
2649
|
+
async load() {
|
|
2650
|
+
const raw = await readFile(this.path, "utf8").catch(() => void 0);
|
|
2651
|
+
if (raw === void 0) return;
|
|
2652
|
+
const parsed = StoreFile.safeParse(JSON.parse(raw));
|
|
2653
|
+
if (!parsed.success) return;
|
|
2654
|
+
for (const thread of parsed.data.threads) {
|
|
2655
|
+
if (thread.status === "starting" && !thread.provider.threadId) {
|
|
2656
|
+
thread.status = "error";
|
|
2657
|
+
thread.statusDetail = "Bridge stopped before the thread was created";
|
|
2658
|
+
}
|
|
2659
|
+
this.#threads.set(thread.id, thread);
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
list() {
|
|
2663
|
+
return [...this.#threads.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
2664
|
+
}
|
|
2665
|
+
get(id) {
|
|
2666
|
+
return this.#threads.get(id);
|
|
2667
|
+
}
|
|
2668
|
+
findByProviderThread(providerId, providerThreadId) {
|
|
2669
|
+
for (const thread of this.#threads.values()) if (thread.provider.id === providerId && thread.provider.threadId === providerThreadId) return thread;
|
|
2670
|
+
}
|
|
2671
|
+
upsert(thread) {
|
|
2672
|
+
this.#threads.set(thread.id, thread);
|
|
2673
|
+
this.#scheduleWrite();
|
|
2674
|
+
}
|
|
2675
|
+
delete(id) {
|
|
2676
|
+
const deleted = this.#threads.delete(id);
|
|
2677
|
+
if (deleted) this.#scheduleWrite();
|
|
2678
|
+
return deleted;
|
|
2679
|
+
}
|
|
2680
|
+
async flush() {
|
|
2681
|
+
if (this.#writeTimer) {
|
|
2682
|
+
clearTimeout(this.#writeTimer);
|
|
2683
|
+
this.#writeTimer = void 0;
|
|
2684
|
+
this.#write();
|
|
2685
|
+
}
|
|
2686
|
+
await this.#writing;
|
|
2687
|
+
}
|
|
2688
|
+
#scheduleWrite() {
|
|
2689
|
+
if (this.#writeTimer) return;
|
|
2690
|
+
this.#writeTimer = setTimeout(() => {
|
|
2691
|
+
this.#writeTimer = void 0;
|
|
2692
|
+
this.#write();
|
|
2693
|
+
}, 250);
|
|
2694
|
+
}
|
|
2695
|
+
#write() {
|
|
2696
|
+
const body = `${JSON.stringify({
|
|
2697
|
+
version: 1,
|
|
2698
|
+
root: this.#root,
|
|
2699
|
+
threads: this.list()
|
|
2700
|
+
}, null, 2)}\n`;
|
|
2701
|
+
this.#writing = this.#writing.then(async () => {
|
|
2702
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
2703
|
+
const temp = `${this.path}.tmp`;
|
|
2704
|
+
await writeFile(temp, body, { mode: 384 });
|
|
2705
|
+
await rename(temp, this.path);
|
|
2706
|
+
});
|
|
2707
|
+
}
|
|
2708
|
+
};
|
|
2709
|
+
//#endregion
|
|
2710
|
+
//#region src/daemon/agents.ts
|
|
2711
|
+
const PROVIDERS = ["t3code", "claude-code"];
|
|
2712
|
+
const PROVIDER_OPTIONS = [{
|
|
2713
|
+
id: "t3code",
|
|
2714
|
+
label: "T3 Code"
|
|
2715
|
+
}, {
|
|
2716
|
+
id: "claude-code",
|
|
2717
|
+
label: "Claude Code"
|
|
2718
|
+
}];
|
|
2719
|
+
const providerLabel = (id) => PROVIDER_OPTIONS.find((option) => option.id === id)?.label ?? id;
|
|
2720
|
+
const SettingsFile$1 = z.object({
|
|
2721
|
+
version: z.literal(1),
|
|
2722
|
+
/** The agent of projects that haven't picked one in the overlay. */
|
|
2723
|
+
provider: z.enum(PROVIDERS).optional()
|
|
2724
|
+
});
|
|
2725
|
+
const settingsPath = (dataDir) => join(dataDir, "settings.json");
|
|
2726
|
+
/** The agent chosen for this machine (by setup or `--provider`), if any. */
|
|
2727
|
+
async function savedProvider(dataDir = defaultDataDir()) {
|
|
2728
|
+
const raw = await readFile(settingsPath(dataDir), "utf8").catch(() => void 0);
|
|
2729
|
+
if (raw === void 0) return void 0;
|
|
2730
|
+
try {
|
|
2731
|
+
const parsed = SettingsFile$1.safeParse(JSON.parse(raw));
|
|
2732
|
+
return parsed.success ? parsed.data.provider : void 0;
|
|
2733
|
+
} catch {
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
async function saveProvider(provider, dataDir = defaultDataDir()) {
|
|
2738
|
+
const path = settingsPath(dataDir);
|
|
2739
|
+
await mkdir(dirname(path), { recursive: true });
|
|
2740
|
+
await writeFile(`${path}.tmp`, `${JSON.stringify({
|
|
2741
|
+
version: 1,
|
|
2742
|
+
provider
|
|
2743
|
+
}, null, 2)}\n`);
|
|
2744
|
+
await rename(`${path}.tmp`, path);
|
|
2745
|
+
}
|
|
2746
|
+
/** Which agents this machine has: a paired or running T3 Code, an installed Claude Code. */
|
|
2747
|
+
async function detectAgents(options = {}) {
|
|
2748
|
+
const [t3code, claudeCode] = await Promise.all([hasT3Code(options.t3Url), hasClaudeCode()]);
|
|
2749
|
+
return {
|
|
2750
|
+
t3code,
|
|
2751
|
+
"claude-code": claudeCode
|
|
2752
|
+
};
|
|
2753
|
+
}
|
|
2754
|
+
/**
|
|
2755
|
+
* The agent for projects that haven't picked one: the saved choice, else the
|
|
2756
|
+
* only agent found, else T3 Code.
|
|
2757
|
+
*/
|
|
2758
|
+
async function machineProvider(options = {}) {
|
|
2759
|
+
const saved = await savedProvider(options.dataDir);
|
|
2760
|
+
if (saved) return saved;
|
|
2761
|
+
const found = await detectAgents(options);
|
|
2762
|
+
return found["claude-code"] && !found.t3code ? "claude-code" : "t3code";
|
|
2763
|
+
}
|
|
2764
|
+
async function hasT3Code(t3Url) {
|
|
2765
|
+
const store = new CredentialStore();
|
|
2766
|
+
const baseUrl = t3Url ?? await store.lastBaseUrl() ?? "http://127.0.0.1:3773";
|
|
2767
|
+
if (await store.get(baseUrl)) return true;
|
|
2768
|
+
try {
|
|
2769
|
+
return (await fetch(new URL("/.well-known/t3/environment", baseUrl), { signal: AbortSignal.timeout(800) })).ok;
|
|
2770
|
+
} catch {
|
|
2771
|
+
return false;
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
/** `claude` on the PATH, or its config folder (login services get a bare PATH). */
|
|
2775
|
+
async function hasClaudeCode() {
|
|
2776
|
+
const names = process.platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"];
|
|
2777
|
+
const candidates = [process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean).flatMap((dir) => names.map((name) => join(dir, name)))];
|
|
2778
|
+
return (await Promise.all(candidates.map((path) => access(path).then(() => true, () => false)))).includes(true);
|
|
2779
|
+
}
|
|
2780
|
+
//#endregion
|
|
2781
|
+
//#region src/daemon/project-providers.ts
|
|
2782
|
+
const SettingsFile = z.object({
|
|
2783
|
+
version: z.literal(1),
|
|
2784
|
+
/** The provider new pins go to; unset means the daemon's `--provider`. */
|
|
2785
|
+
provider: z.string().optional()
|
|
2786
|
+
});
|
|
2787
|
+
/**
|
|
2788
|
+
* The providers of one project. New pins go to the project's default, which
|
|
2789
|
+
* the overlay's settings change; existing pins keep the provider they were
|
|
2790
|
+
* made with. Providers are created and started on first use.
|
|
2791
|
+
*/
|
|
2792
|
+
var ProjectProviders = class ProjectProviders {
|
|
2793
|
+
choices;
|
|
2794
|
+
#options;
|
|
2795
|
+
#providers = /* @__PURE__ */ new Map();
|
|
2796
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
2797
|
+
#chosen;
|
|
2798
|
+
constructor(options) {
|
|
2799
|
+
this.#options = options;
|
|
2800
|
+
this.choices = options.choices;
|
|
2801
|
+
}
|
|
2802
|
+
/** One fixed provider and no settings file (tests). */
|
|
2803
|
+
static of(provider) {
|
|
2804
|
+
const providers = new ProjectProviders({
|
|
2805
|
+
choices: [{
|
|
2806
|
+
id: provider.id,
|
|
2807
|
+
label: provider.label
|
|
2808
|
+
}],
|
|
2809
|
+
fallback: provider.id,
|
|
2810
|
+
create: () => provider
|
|
2811
|
+
});
|
|
2812
|
+
providers.get(provider.id);
|
|
2813
|
+
return providers;
|
|
2814
|
+
}
|
|
2815
|
+
async load() {
|
|
2816
|
+
if (!this.#options.settingsPath) return;
|
|
2817
|
+
const raw = await readFile(this.#options.settingsPath, "utf8").catch(() => void 0);
|
|
2818
|
+
const parsed = raw === void 0 ? void 0 : SettingsFile.safeParse(JSON.parse(raw));
|
|
2819
|
+
if (parsed?.success) this.#chosen = parsed.data.provider;
|
|
2820
|
+
}
|
|
2821
|
+
get defaultId() {
|
|
2822
|
+
const chosen = this.#chosen;
|
|
2823
|
+
return chosen && this.choices.some((choice) => choice.id === chosen) ? chosen : this.#options.fallback;
|
|
2824
|
+
}
|
|
2825
|
+
default() {
|
|
2826
|
+
return this.get(this.defaultId);
|
|
2827
|
+
}
|
|
2828
|
+
/** Can pins of this provider be served (a choice, or one already running)? */
|
|
2829
|
+
has(id) {
|
|
2830
|
+
return this.#providers.has(id) || this.choices.some((choice) => choice.id === id);
|
|
2831
|
+
}
|
|
2832
|
+
get(id) {
|
|
2833
|
+
let provider = this.#providers.get(id);
|
|
2834
|
+
if (!provider) {
|
|
2835
|
+
provider = this.#options.create(id);
|
|
2836
|
+
this.#providers.set(id, provider);
|
|
2837
|
+
if (provider.id !== id) this.#providers.set(provider.id, provider);
|
|
2838
|
+
provider.start();
|
|
2839
|
+
}
|
|
2840
|
+
return provider;
|
|
2841
|
+
}
|
|
2842
|
+
async setDefault(id) {
|
|
2843
|
+
if (!this.choices.some((choice) => choice.id === id)) throw new Error(`Unknown provider "${id}"`);
|
|
2844
|
+
if (id === this.defaultId) return;
|
|
2845
|
+
this.#chosen = id;
|
|
2846
|
+
await this.#save();
|
|
2847
|
+
for (const listener of this.#listeners) listener();
|
|
2848
|
+
}
|
|
2849
|
+
onDefaultChange(listener) {
|
|
2850
|
+
this.#listeners.add(listener);
|
|
2851
|
+
return () => this.#listeners.delete(listener);
|
|
2852
|
+
}
|
|
2853
|
+
async dispose() {
|
|
2854
|
+
await Promise.all([...new Set(this.#providers.values())].map((p) => p.dispose()));
|
|
2855
|
+
this.#providers.clear();
|
|
2856
|
+
}
|
|
2857
|
+
async #save() {
|
|
2858
|
+
const path = this.#options.settingsPath;
|
|
2859
|
+
if (!path) return;
|
|
2860
|
+
await mkdir(dirname(path), { recursive: true });
|
|
2861
|
+
const temp = `${path}.tmp`;
|
|
2862
|
+
await writeFile(temp, `${JSON.stringify({
|
|
2863
|
+
version: 1,
|
|
2864
|
+
provider: this.#chosen
|
|
2865
|
+
}, null, 2)}\n`);
|
|
2866
|
+
await rename(temp, path);
|
|
2867
|
+
}
|
|
2868
|
+
};
|
|
2869
|
+
//#endregion
|
|
2870
|
+
//#region src/daemon/security.ts
|
|
2871
|
+
/**
|
|
2872
|
+
* The bridge can make an agent edit code, so only pages the developer runs
|
|
2873
|
+
* locally (or explicitly allowed with `--allow-origin`) may talk to it.
|
|
2874
|
+
* Browsers always send Origin on WebSocket upgrades; a request without one
|
|
2875
|
+
* comes from a non-browser tool, which is only trusted on this machine.
|
|
2876
|
+
*/
|
|
2877
|
+
function isAllowedOrigin(request, allowedOrigins) {
|
|
2878
|
+
const origin = request.headers.origin;
|
|
2879
|
+
if (!origin) return isLoopbackAddress(request.socket.remoteAddress);
|
|
2880
|
+
if (allowedOrigins.includes("*") || allowedOrigins.includes(origin)) return true;
|
|
2881
|
+
let hostname;
|
|
2882
|
+
try {
|
|
2883
|
+
hostname = new URL(origin).hostname;
|
|
2884
|
+
} catch {
|
|
2885
|
+
return false;
|
|
2886
|
+
}
|
|
2887
|
+
return isLoopbackName(hostname);
|
|
2888
|
+
}
|
|
2889
|
+
/**
|
|
2890
|
+
* DNS rebinding guard: a hostile domain re-pointed at this machine still sends
|
|
2891
|
+
* its own name as Host. Only loopback names and the names we were told about
|
|
2892
|
+
* (listen addresses, allowed origins' hosts) may talk to us.
|
|
2893
|
+
*/
|
|
2894
|
+
function isAllowedHost(request, knownHosts) {
|
|
2895
|
+
const header = request.headers.host;
|
|
2896
|
+
if (!header) return false;
|
|
2897
|
+
let hostname;
|
|
2898
|
+
try {
|
|
2899
|
+
hostname = new URL(`http://${header}`).hostname;
|
|
2900
|
+
} catch {
|
|
2901
|
+
return false;
|
|
2902
|
+
}
|
|
2903
|
+
return isLoopbackName(hostname) || knownHosts.includes(hostname);
|
|
2904
|
+
}
|
|
2905
|
+
/** Host names a request may be addressed to, besides loopback ones. */
|
|
2906
|
+
function knownHostsFor(listen, allowedOrigins) {
|
|
2907
|
+
const hosts = new Set(listen);
|
|
2908
|
+
for (const origin of allowedOrigins) try {
|
|
2909
|
+
hosts.add(new URL(origin).hostname);
|
|
2910
|
+
} catch {}
|
|
2911
|
+
return [...hosts];
|
|
2912
|
+
}
|
|
2913
|
+
function isLoopbackName(hostname) {
|
|
2914
|
+
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(hostname);
|
|
2915
|
+
}
|
|
2916
|
+
function isLoopbackAddress(address) {
|
|
2917
|
+
if (!address) return false;
|
|
2918
|
+
const ip = address.replace(/^::ffff:/, "");
|
|
2919
|
+
return ip === "::1" || /^127(?:\.\d{1,3}){3}$/.test(ip);
|
|
2920
|
+
}
|
|
2921
|
+
//#endregion
|
|
2922
|
+
//#region src/daemon/server.ts
|
|
2923
|
+
const DEFAULT_PORT = 4747;
|
|
2924
|
+
/** Screenshots ride along as data URLs. */
|
|
2925
|
+
const MAX_PAYLOAD_BYTES = 33554432;
|
|
2926
|
+
/**
|
|
2927
|
+
* One Tencil daemon per machine. Pages load `/tencil.js` from it; each
|
|
2928
|
+
* page's WebSocket is attached to the project it belongs to (worked out from
|
|
2929
|
+
* the dev server's port, or picked by the user), and every project gets its
|
|
2930
|
+
* own bridge, provider connection and pin store, created on first use.
|
|
2931
|
+
*/
|
|
2932
|
+
async function startDaemon(options = {}) {
|
|
2933
|
+
const port = options.port ?? 4747;
|
|
2934
|
+
const host = options.host ?? "127.0.0.1";
|
|
2935
|
+
const addresses = [host, ...(options.listen ?? []).filter((address) => address !== host)];
|
|
2936
|
+
const allowedOrigins = options.allowedOrigins ?? [];
|
|
2937
|
+
const knownHosts = knownHostsFor(addresses, allowedOrigins);
|
|
2938
|
+
const dataDir = options.dataDir ?? defaultDataDir();
|
|
2939
|
+
const log = options.log ?? (() => {});
|
|
2940
|
+
const resolver = new ProjectResolver({
|
|
2941
|
+
dataDir,
|
|
2942
|
+
exec: options.exec
|
|
2943
|
+
});
|
|
2944
|
+
const resolveProject = options.resolveProject ?? ((pageUrl) => resolver.resolve(pageUrl));
|
|
2945
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
2946
|
+
const overlayPath = resolveOverlayPath();
|
|
2947
|
+
const claudeCodeDir = join(dataDir, "claude-code");
|
|
2948
|
+
const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
|
|
2949
|
+
const createProvider = options.createProvider ?? ((root, id) => {
|
|
2950
|
+
const providerLog = (message) => log(`[${basename(root)}] ${message}`);
|
|
2951
|
+
if (id === "claude-code") return new ClaudeCodeProvider({
|
|
2952
|
+
...options.claudeCode,
|
|
2953
|
+
projectRoot: root,
|
|
2954
|
+
installDir: claudeCodeDir,
|
|
2955
|
+
log: providerLog
|
|
2956
|
+
});
|
|
2957
|
+
const { url, token, ...t3 } = options.t3 ?? {};
|
|
2958
|
+
return new T3CodeProvider({
|
|
2959
|
+
...t3,
|
|
2960
|
+
projectRoot: root,
|
|
2961
|
+
baseUrl: t3Url,
|
|
2962
|
+
token: token ?? process.env.TENCIL_T3_TOKEN,
|
|
2963
|
+
createProjectIfMissing: t3.createProjectIfMissing ?? true,
|
|
2964
|
+
log: providerLog
|
|
2965
|
+
});
|
|
2966
|
+
});
|
|
2967
|
+
const session = (root) => {
|
|
2968
|
+
const key = resolve(root);
|
|
2969
|
+
let pending = sessions.get(key);
|
|
2970
|
+
if (!pending) {
|
|
2971
|
+
pending = (async () => {
|
|
2972
|
+
const providers = new ProjectProviders({
|
|
2973
|
+
choices: PROVIDER_OPTIONS,
|
|
2974
|
+
fallback: options.provider ?? await machineProvider({
|
|
2975
|
+
dataDir,
|
|
2976
|
+
t3Url
|
|
2977
|
+
}),
|
|
2978
|
+
create: (id) => createProvider(key, id),
|
|
2979
|
+
settingsPath: projectStorePath(key, dataDir).replace(/\.json$/, ".settings.json")
|
|
2980
|
+
});
|
|
2981
|
+
const store = new ThreadStore(key, dataDir);
|
|
2982
|
+
await Promise.all([store.load(), providers.load()]);
|
|
2983
|
+
const bridge = new Bridge({
|
|
2984
|
+
providers,
|
|
2985
|
+
store,
|
|
2986
|
+
project: {
|
|
2987
|
+
name: basename(key),
|
|
2988
|
+
root: key
|
|
2989
|
+
},
|
|
2990
|
+
version: VERSION,
|
|
2991
|
+
log: (message) => log(`[${basename(key)}] ${message}`)
|
|
2992
|
+
});
|
|
2993
|
+
log(`Serving ${key} with ${providers.default().label}`);
|
|
2994
|
+
return {
|
|
2995
|
+
root: key,
|
|
2996
|
+
bridge,
|
|
2997
|
+
providers,
|
|
2998
|
+
clients: 0
|
|
2999
|
+
};
|
|
3000
|
+
})();
|
|
3001
|
+
sessions.set(key, pending);
|
|
3002
|
+
}
|
|
3003
|
+
return pending;
|
|
3004
|
+
};
|
|
3005
|
+
/** Projects either agent knows, offered when a page's project can't be worked out. */
|
|
3006
|
+
const choices = async () => {
|
|
3007
|
+
const [t3, claude] = await Promise.all([listT3Projects({
|
|
3008
|
+
baseUrl: t3Url,
|
|
3009
|
+
token: options.t3?.token ?? process.env.TENCIL_T3_TOKEN,
|
|
3010
|
+
credentials: options.t3?.credentials
|
|
3011
|
+
}).catch(() => []), listClaudeCodeProjects({ installDir: claudeCodeDir }).catch(() => [])]);
|
|
3012
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
3013
|
+
for (const project of [...t3, ...claude]) if (!byRoot.has(project.workspaceRoot)) byRoot.set(project.workspaceRoot, {
|
|
3014
|
+
root: project.workspaceRoot,
|
|
3015
|
+
title: project.title
|
|
3016
|
+
});
|
|
3017
|
+
return [...byRoot.values()];
|
|
3018
|
+
};
|
|
3019
|
+
const noChoicesHint = "No projects found. Open this page's project in T3 Code, or run claude in it once.";
|
|
3020
|
+
const settled = async () => (await Promise.allSettled(sessions.values())).filter((r) => r.status === "fulfilled").map((r) => r.value);
|
|
3021
|
+
let statuses = [];
|
|
3022
|
+
const refreshStatuses = async () => {
|
|
3023
|
+
statuses = (await settled()).map((s) => ({
|
|
3024
|
+
root: s.root,
|
|
3025
|
+
name: basename(s.root),
|
|
3026
|
+
clients: s.clients,
|
|
3027
|
+
provider: s.providers.default().info()
|
|
3028
|
+
}));
|
|
3029
|
+
};
|
|
3030
|
+
const handleRequest = async (request, response) => {
|
|
3031
|
+
if (!isAllowedHost(request, knownHosts)) {
|
|
3032
|
+
response.writeHead(403, { "content-type": "text/plain" });
|
|
3033
|
+
response.end("Forbidden host");
|
|
3034
|
+
return;
|
|
3035
|
+
}
|
|
3036
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
3037
|
+
if (url.pathname === "/tencil.js") {
|
|
3038
|
+
try {
|
|
3039
|
+
const body = await readFile(overlayPath);
|
|
3040
|
+
response.writeHead(200, {
|
|
3041
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
3042
|
+
"cache-control": "no-cache",
|
|
3043
|
+
"access-control-allow-origin": "*"
|
|
3044
|
+
});
|
|
3045
|
+
response.end(body);
|
|
3046
|
+
} catch {
|
|
3047
|
+
response.writeHead(500, { "content-type": "text/plain" });
|
|
3048
|
+
response.end(`Overlay bundle missing at ${overlayPath}. Build it first.`);
|
|
3049
|
+
}
|
|
3050
|
+
return;
|
|
3051
|
+
}
|
|
3052
|
+
if (url.pathname === "/health") {
|
|
3053
|
+
await refreshStatuses();
|
|
3054
|
+
response.writeHead(200, { "content-type": "application/json" });
|
|
3055
|
+
response.end(JSON.stringify({
|
|
3056
|
+
name: "tencil",
|
|
3057
|
+
version: VERSION,
|
|
3058
|
+
pid: process.pid,
|
|
3059
|
+
flags: options.flags ?? [],
|
|
3060
|
+
projects: statuses
|
|
3061
|
+
}));
|
|
3062
|
+
return;
|
|
3063
|
+
}
|
|
3064
|
+
response.writeHead(404, { "content-type": "text/plain" });
|
|
3065
|
+
response.end("Not found");
|
|
3066
|
+
};
|
|
3067
|
+
const wss = new WebSocketServer({
|
|
3068
|
+
noServer: true,
|
|
3069
|
+
maxPayload: MAX_PAYLOAD_BYTES
|
|
3070
|
+
});
|
|
3071
|
+
const handleUpgrade = (request, socket, head) => {
|
|
3072
|
+
if (new URL(request.url ?? "/", "http://localhost").pathname !== "/ws" || !isAllowedHost(request, knownHosts) || !isAllowedOrigin(request, allowedOrigins)) {
|
|
3073
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
3074
|
+
socket.destroy();
|
|
3075
|
+
return;
|
|
3076
|
+
}
|
|
3077
|
+
wss.handleUpgrade(request, socket, head, (ws) => serveClient(ws));
|
|
3078
|
+
};
|
|
3079
|
+
/** A page connection: resolve its project on `hello`, then relay to that project's bridge. */
|
|
3080
|
+
function serveClient(ws) {
|
|
3081
|
+
const client = { send: (message) => {
|
|
3082
|
+
if (ws.readyState === WebSocket$1.OPEN) ws.send(JSON.stringify(message));
|
|
3083
|
+
} };
|
|
3084
|
+
let current;
|
|
3085
|
+
let detach;
|
|
3086
|
+
let pageUrl = "";
|
|
3087
|
+
let queue = Promise.resolve();
|
|
3088
|
+
const attach = async (root, hello) => {
|
|
3089
|
+
detach?.();
|
|
3090
|
+
if (current) current.clients--;
|
|
3091
|
+
current = await session(root);
|
|
3092
|
+
current.clients++;
|
|
3093
|
+
detach = current.bridge.connect(client);
|
|
3094
|
+
await current.bridge.handle(client, hello);
|
|
3095
|
+
};
|
|
3096
|
+
const handle = async (raw) => {
|
|
3097
|
+
const message = raw;
|
|
3098
|
+
if (message.type === "hello") {
|
|
3099
|
+
pageUrl = message.pageUrl ?? "";
|
|
3100
|
+
const root = await resolveProject(pageUrl).catch(() => void 0);
|
|
3101
|
+
if (root) return attach(root, raw);
|
|
3102
|
+
return client.send({
|
|
3103
|
+
type: "project.unknown",
|
|
3104
|
+
pageUrl,
|
|
3105
|
+
choices: await choices(),
|
|
3106
|
+
emptyHint: noChoicesHint
|
|
3107
|
+
});
|
|
3108
|
+
}
|
|
3109
|
+
if (message.type === "project.select" && message.root) {
|
|
3110
|
+
await resolver.remember(pageUrl, message.root);
|
|
3111
|
+
return attach(message.root, {
|
|
3112
|
+
type: "hello",
|
|
3113
|
+
protocol: 1,
|
|
3114
|
+
pageUrl
|
|
3115
|
+
});
|
|
3116
|
+
}
|
|
3117
|
+
if (!current) return client.send({
|
|
3118
|
+
type: "error",
|
|
3119
|
+
message: "No project selected yet"
|
|
3120
|
+
});
|
|
3121
|
+
await current.bridge.handle(client, raw);
|
|
3122
|
+
};
|
|
3123
|
+
ws.on("message", (data) => {
|
|
3124
|
+
let parsed;
|
|
3125
|
+
try {
|
|
3126
|
+
parsed = JSON.parse(String(data));
|
|
3127
|
+
} catch {
|
|
3128
|
+
return client.send({
|
|
3129
|
+
type: "error",
|
|
3130
|
+
message: "Malformed JSON"
|
|
3131
|
+
});
|
|
3132
|
+
}
|
|
3133
|
+
queue = queue.then(() => handle(parsed)).catch((error) => {
|
|
3134
|
+
client.send({
|
|
3135
|
+
type: "error",
|
|
3136
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3137
|
+
});
|
|
3138
|
+
});
|
|
3139
|
+
});
|
|
3140
|
+
ws.on("close", () => {
|
|
3141
|
+
detach?.();
|
|
3142
|
+
if (current) current.clients--;
|
|
3143
|
+
});
|
|
3144
|
+
}
|
|
3145
|
+
const listenOn = (address, listenPort) => new Promise((resolveListen, reject) => {
|
|
3146
|
+
const server = createServer(handleRequest);
|
|
3147
|
+
server.on("upgrade", handleUpgrade);
|
|
3148
|
+
server.once("error", reject);
|
|
3149
|
+
server.listen(listenPort, address, () => {
|
|
3150
|
+
server.off("error", reject);
|
|
3151
|
+
resolveListen(server);
|
|
3152
|
+
});
|
|
3153
|
+
});
|
|
3154
|
+
const servers = [await listenOn(host, port)];
|
|
3155
|
+
const address = servers[0]?.address();
|
|
3156
|
+
const actualPort = typeof address === "object" && address ? address.port : port;
|
|
3157
|
+
try {
|
|
3158
|
+
for (const extra of addresses.slice(1)) servers.push(await listenOn(extra, actualPort));
|
|
3159
|
+
} catch (error) {
|
|
3160
|
+
for (const server of servers) server.close();
|
|
3161
|
+
throw error;
|
|
3162
|
+
}
|
|
3163
|
+
const url = `http://${host === "127.0.0.1" || host === "0.0.0.0" ? "localhost" : host}:${actualPort}`;
|
|
3164
|
+
log(`Tencil daemon listening on ${url}`);
|
|
3165
|
+
for (const extra of addresses.slice(1)) log(`Also listening on http://${extra}:${actualPort}`);
|
|
3166
|
+
return {
|
|
3167
|
+
url,
|
|
3168
|
+
scriptUrl: `${url}/tencil.js`,
|
|
3169
|
+
port: actualPort,
|
|
3170
|
+
projects: () => statuses,
|
|
3171
|
+
async close() {
|
|
3172
|
+
for (const ws of wss.clients) ws.terminate();
|
|
3173
|
+
for (const s of await settled()) {
|
|
3174
|
+
await s.bridge.dispose();
|
|
3175
|
+
await s.providers.dispose();
|
|
3176
|
+
}
|
|
3177
|
+
await Promise.all(servers.map((server) => new Promise((done) => server.close(() => done()))));
|
|
3178
|
+
}
|
|
3179
|
+
};
|
|
3180
|
+
}
|
|
3181
|
+
/** Is a Tencil daemon answering on this port? Returns its health report. */
|
|
3182
|
+
async function probeDaemon(port = DEFAULT_PORT, host = "127.0.0.1") {
|
|
3183
|
+
try {
|
|
3184
|
+
const body = await (await fetch(`http://${host}:${port}/health`, { signal: AbortSignal.timeout(1500) })).json();
|
|
3185
|
+
return body.name === "tencil" ? {
|
|
3186
|
+
version: body.version,
|
|
3187
|
+
pid: body.pid,
|
|
3188
|
+
flags: body.flags ?? [],
|
|
3189
|
+
projects: body.projects ?? []
|
|
3190
|
+
} : void 0;
|
|
3191
|
+
} catch {
|
|
3192
|
+
return;
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
/** Published builds ship the overlay next to this file; the monorepo uses the workspace build. */
|
|
3196
|
+
function resolveOverlayPath() {
|
|
3197
|
+
const candidates = [
|
|
3198
|
+
fileURLToPath(new URL("./overlay.global.js", import.meta.url)),
|
|
3199
|
+
fileURLToPath(new URL("../../overlay/dist/tencil.global.js", import.meta.url)),
|
|
3200
|
+
fileURLToPath(new URL("../../../overlay/dist/tencil.global.js", import.meta.url))
|
|
3201
|
+
];
|
|
3202
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
|
|
3203
|
+
}
|
|
3204
|
+
//#endregion
|
|
3205
|
+
export { renderPrompt as C, Bridge as S, parsePairingInput as _, detectAgents as a, ProjectResolver as b, savedProvider as c, projectStorePath as d, VERSION as f, exchangePairingCredential as g, createLocalPairingCode as h, PROVIDERS as i, ThreadStore as l, DEFAULT_T3_URL as m, probeDaemon as n, providerLabel as o, CredentialStore as p, startDaemon as r, saveProvider as s, DEFAULT_PORT as t, defaultDataDir as u, withoutNpmEnv as v, stripContext as w, projectRoot as x, loadAgentSdk as y };
|