tencil 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,11 +64,24 @@ const ImageAttachment = z.object({
64
64
  ]),
65
65
  dataUrl: z.string().startsWith("data:image/").max(14e6)
66
66
  });
67
+ /**
68
+ * The code a page was built from, set by Tencil Cloud builds (`TENCIL_CLOUD`).
69
+ * Local pages have none: the daemon finds their project from the dev server.
70
+ */
71
+ const BuildInfo = z.object({
72
+ /** Project key from the Tencil Cloud dashboard. */
73
+ projectKey: z.string().min(1).max(64),
74
+ /** `owner/name` on GitHub. */
75
+ repo: z.string().min(3).max(200),
76
+ branch: z.string().min(1).max(255),
77
+ sha: z.string().min(7).max(64)
78
+ });
67
79
  const ClientMessage = z.discriminatedUnion("type", [
68
80
  z.object({
69
81
  type: z.literal("hello"),
70
82
  protocol: z.literal(1),
71
- pageUrl: z.string()
83
+ pageUrl: z.string(),
84
+ build: BuildInfo.optional()
72
85
  }),
73
86
  z.object({
74
87
  type: z.literal("thread.create"),
@@ -80,7 +93,22 @@ const ClientMessage = z.discriminatedUnion("type", [
80
93
  context: ElementContext,
81
94
  attachments: z.array(ImageAttachment).max(4).default([]),
82
95
  /** Continue this existing provider thread instead of starting a new one. */
83
- providerThreadId: z.string().optional()
96
+ providerThreadId: z.string().optional(),
97
+ /** Queue it for a batch (`drafts.send`) instead of sending it now. */
98
+ draft: z.boolean().optional()
99
+ }),
100
+ z.object({
101
+ type: z.literal("thread.edit"),
102
+ threadId: z.string(),
103
+ prompt: z.string().min(1)
104
+ }),
105
+ z.object({
106
+ type: z.literal("drafts.send"),
107
+ /** In pin order; `number` is the pin's number, which the agent refers to. */
108
+ drafts: z.array(z.object({
109
+ threadId: z.string(),
110
+ number: z.number().int().positive()
111
+ })).min(1)
84
112
  }),
85
113
  z.object({
86
114
  type: z.literal("thread.open"),
@@ -89,6 +117,7 @@ const ClientMessage = z.discriminatedUnion("type", [
89
117
  title: z.string().optional()
90
118
  }),
91
119
  z.object({ type: z.literal("provider.threads") }),
120
+ z.object({ type: z.literal("provider.models") }),
92
121
  z.object({
93
122
  type: z.literal("project.select"),
94
123
  root: z.string().min(1)
@@ -113,9 +142,19 @@ const ClientMessage = z.discriminatedUnion("type", [
113
142
  type: z.literal("thread.delete"),
114
143
  threadId: z.string()
115
144
  }),
145
+ z.object({
146
+ type: z.literal("thread.move"),
147
+ threadId: z.string(),
148
+ anchor: Anchor
149
+ }),
116
150
  z.object({
117
151
  type: z.literal("settings.update"),
118
- provider: z.string().min(1)
152
+ provider: z.string().min(1).optional(),
153
+ batch: z.boolean().optional()
154
+ }),
155
+ z.object({
156
+ type: z.literal("model.select"),
157
+ model: z.string().min(1).nullable()
119
158
  })
120
159
  ]);
121
160
  z.object({
@@ -141,12 +180,17 @@ const ProviderOption = z.object({
141
180
  z.object({
142
181
  /** Provider new pins go to; existing pins keep their own. */
143
182
  provider: z.string(),
144
- providers: z.array(ProviderOption)
183
+ providers: z.array(ProviderOption),
184
+ /** Model picked for the provider's new threads; unset means the provider's default. */
185
+ model: z.string().optional(),
186
+ /** New comments are queued and sent together. */
187
+ batch: z.boolean()
145
188
  });
146
189
  //#endregion
147
190
  //#region ../protocol/src/thread.ts
148
191
  /**
149
192
  * Provider-agnostic run state.
193
+ * - `draft`: a comment queued in a batch, not sent to the agent yet
150
194
  * - `starting`: thread is being created on the provider
151
195
  * - `working`: the agent is producing a turn
152
196
  * - `waiting`: the agent needs approval/input inside the provider UI
@@ -154,6 +198,7 @@ z.object({
154
198
  * - `error`: last turn or the thread itself failed
155
199
  */
156
200
  const ThreadStatus = z.enum([
201
+ "draft",
157
202
  "starting",
158
203
  "working",
159
204
  "waiting",
@@ -219,6 +264,15 @@ z.object({
219
264
  /** Agent driver, e.g. `codex` or `claudeAgent`, for the provider icon. */
220
265
  agent: z.string().optional()
221
266
  });
267
+ z.object({
268
+ /** Opaque to the overlay; the provider parses it back. */
269
+ id: z.string(),
270
+ label: z.string(),
271
+ /** The agent it belongs to, e.g. "Claude" or "Codex". */
272
+ group: z.string(),
273
+ /** Agent kind for its icon (`codex`, `claudeAgent`). */
274
+ agent: z.string().optional()
275
+ });
222
276
  z.object({
223
277
  name: z.string(),
224
278
  /** Absolute URL of the project's favicon, if it has one. */
@@ -226,7 +280,7 @@ z.object({
226
280
  emoji: z.string().optional()
227
281
  });
228
282
  //#endregion
229
- //#region src/daemon/prompt.ts
283
+ //#region ../bridge/src/prompt.ts
230
284
  const CONTEXT_OPEN = "<tencil-context>";
231
285
  const CONTEXT_CLOSE = "</tencil-context>";
232
286
  /**
@@ -235,13 +289,29 @@ const CONTEXT_CLOSE = "</tencil-context>";
235
289
  * shown in the overlay (`stripContext`).
236
290
  */
237
291
  function renderPrompt(input) {
238
- const { context } = input;
239
292
  const lines = [
240
293
  "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
294
  "",
242
- `- Page: ${input.pageUrl}`,
243
- `- Element: \`${oneLine(context.html)}\``
295
+ ...contextLines(input.pageUrl, input.context)
244
296
  ];
297
+ if (input.hasScreenshot) lines.push("- A screenshot of the element is attached.");
298
+ return `${input.prompt.trim()}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
299
+ }
300
+ /**
301
+ * Several queued comments as one message: the comments first, numbered like
302
+ * their pins, then one context block with a section per comment. Stripping
303
+ * the block leaves the numbered comments.
304
+ */
305
+ function renderBatchPrompt(comments) {
306
+ const lines = [`The user pinned ${comments.length} comments on elements of their running app (via Tencil). Work through all of them in this workspace, using the context below to locate the code. They're numbered like the pins on the page: refer to them by number (#2) when you report back.`];
307
+ for (const comment of comments) {
308
+ lines.push("", `#${comment.number}`, ...contextLines(comment.pageUrl, comment.context));
309
+ if (comment.screenshots.length > 0) lines.push(`- Screenshot: attached image ${comment.screenshots.join(", ")}`);
310
+ }
311
+ return `${comments.map((comment) => `#${comment.number} ${comment.prompt.trim()}`).join("\n\n")}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
312
+ }
313
+ function contextLines(pageUrl, context) {
314
+ const lines = [`- Page: ${pageUrl}`, `- Element: \`${oneLine(context.html)}\``];
245
315
  const [component, ...owners] = context.components;
246
316
  if (component) {
247
317
  const chain = [component, ...owners.slice(0, 4)].map(formatFrame).join(" ← ");
@@ -252,8 +322,7 @@ function renderPrompt(input) {
252
322
  if (context.selection) lines.push(`- Selected text: "${truncate(oneLine(context.selection), 300)}"`);
253
323
  const { rect, viewport } = context;
254
324
  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}`;
325
+ return lines;
257
326
  }
258
327
  function stripContext(text) {
259
328
  const index = text.indexOf(CONTEXT_OPEN);
@@ -263,6 +332,9 @@ function titleFor(prompt, context) {
263
332
  const firstLine = prompt.trim().split("\n", 1)[0] ?? "";
264
333
  return truncate(`${context.components[0]?.name ?? `<${context.tagName}>`}: ${firstLine}`, 80);
265
334
  }
335
+ function batchTitle(titles) {
336
+ return truncate(`${titles.length} comments: ${titles.join(" · ")}`, 80);
337
+ }
266
338
  function formatFrame(frame) {
267
339
  if (frame.library) return `${frame.name} (${frame.library})`;
268
340
  if (!frame.source) return frame.name;
@@ -276,7 +348,7 @@ function truncate(text, max) {
276
348
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
277
349
  }
278
350
  //#endregion
279
- //#region src/daemon/bridge.ts
351
+ //#region ../bridge/src/bridge.ts
280
352
  /** Local echo ids, replaced once the provider reports the real user message. */
281
353
  const LOCAL_PREFIX = "local:";
282
354
  const BROADCAST_THROTTLE_MS = 80;
@@ -290,8 +362,11 @@ var Bridge = class {
290
362
  /** One provider subscription per provider thread, shared by every pin bound to it. */
291
363
  #watches = /* @__PURE__ */ new Map();
292
364
  #pendingBroadcast = /* @__PURE__ */ new Map();
365
+ /** Screenshots of queued comments, kept in memory until the batch is sent. */
366
+ #draftAttachments = /* @__PURE__ */ new Map();
293
367
  #offInfo = () => {};
294
368
  #offDefault;
369
+ #offSettings;
295
370
  constructor(options) {
296
371
  this.#options = options;
297
372
  this.#followDefault();
@@ -306,6 +381,10 @@ var Bridge = class {
306
381
  provider: this.#provider().info()
307
382
  });
308
383
  });
384
+ this.#offSettings = options.providers.onSettingsChange(() => this.#broadcast({
385
+ type: "settings",
386
+ settings: this.#settings()
387
+ }));
309
388
  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
389
  }
311
390
  connect(client) {
@@ -336,7 +415,26 @@ var Bridge = class {
336
415
  });
337
416
  return;
338
417
  case "thread.create":
339
- await (message.providerThreadId ? this.#continue(message) : this.#create(message));
418
+ if (message.draft) this.#queue(message);
419
+ else if (message.providerThreadId) await this.#continue(message);
420
+ else await this.#create(message);
421
+ return;
422
+ case "thread.edit": {
423
+ const draft = this.#require(message.threadId);
424
+ if (draft.status !== "draft") throw new Error("Only queued comments can be edited");
425
+ const [first] = draft.messages;
426
+ this.#update(draft.id, (thread) => ({
427
+ ...thread,
428
+ title: thread.context ? titleFor(message.prompt, thread.context) : message.prompt,
429
+ messages: first ? [{
430
+ ...first,
431
+ text: message.prompt
432
+ }] : []
433
+ }));
434
+ return;
435
+ }
436
+ case "drafts.send":
437
+ await this.#sendDrafts(message.drafts);
340
438
  return;
341
439
  case "thread.open":
342
440
  this.#open(message);
@@ -350,9 +448,26 @@ var Bridge = class {
350
448
  ...await this.#provider().listThreads()
351
449
  });
352
450
  return;
353
- case "settings.update":
354
- await this.#options.providers.setDefault(message.provider);
451
+ case "settings.update": {
452
+ const { providers } = this.#options;
453
+ if (message.provider) await providers.setDefault(message.provider);
454
+ if (message.batch !== void 0) await providers.setBatch(message.batch);
455
+ return;
456
+ }
457
+ case "provider.models": {
458
+ const provider = this.#provider();
459
+ client.send({
460
+ type: "provider.models",
461
+ provider: provider.id,
462
+ ...await provider.listModels?.() ?? { models: [] }
463
+ });
464
+ return;
465
+ }
466
+ case "model.select": {
467
+ const { providers } = this.#options;
468
+ await providers.setModel(providers.defaultId, message.model);
355
469
  return;
470
+ }
356
471
  case "thread.reply":
357
472
  await this.#reply(message);
358
473
  return;
@@ -367,8 +482,15 @@ var Bridge = class {
367
482
  resolved: message.resolved
368
483
  }));
369
484
  return;
485
+ case "thread.move":
486
+ this.#update(message.threadId, (thread) => ({
487
+ ...thread,
488
+ anchor: message.anchor
489
+ }));
490
+ return;
370
491
  case "thread.delete": {
371
492
  const provider = this.#options.store.get(message.threadId)?.provider;
493
+ this.#draftAttachments.delete(message.threadId);
372
494
  if (this.#options.store.delete(message.threadId)) this.#broadcast({
373
495
  type: "thread.removed",
374
496
  threadId: message.threadId
@@ -389,6 +511,7 @@ var Bridge = class {
389
511
  async dispose() {
390
512
  this.#offInfo();
391
513
  this.#offDefault();
514
+ this.#offSettings();
392
515
  for (const unwatch of this.#watches.values()) unwatch();
393
516
  for (const timer of this.#pendingBroadcast.values()) clearTimeout(timer);
394
517
  await this.#options.store.flush();
@@ -422,7 +545,8 @@ var Bridge = class {
422
545
  context: message.context,
423
546
  hasScreenshot: message.attachments.length > 0
424
547
  }),
425
- attachments: message.attachments
548
+ attachments: message.attachments,
549
+ model: this.#options.providers.modelFor(provider.id)
426
550
  });
427
551
  this.#update(thread.id, (current) => ({
428
552
  ...current,
@@ -443,6 +567,96 @@ var Bridge = class {
443
567
  }));
444
568
  }
445
569
  }
570
+ /** Pin a comment without sending it: it waits for `drafts.send`. */
571
+ #queue(message) {
572
+ const { store } = this.#options;
573
+ if (store.get(message.id)) throw new Error(`Thread ${message.id} already exists`);
574
+ const now = (/* @__PURE__ */ new Date()).toISOString();
575
+ store.upsert({
576
+ id: message.id,
577
+ title: titleFor(message.prompt, message.context),
578
+ pageUrl: message.pageUrl,
579
+ anchor: message.anchor,
580
+ context: message.context,
581
+ status: "draft",
582
+ resolved: false,
583
+ messages: [localMessage(message.prompt, now)],
584
+ provider: { id: this.#provider().id },
585
+ createdAt: now,
586
+ updatedAt: now
587
+ });
588
+ if (message.attachments.length > 0) this.#draftAttachments.set(message.id, message.attachments);
589
+ this.#broadcastThread(store.get(message.id), true);
590
+ }
591
+ /** Queued comments go out together: one message, one new provider thread, shared by their pins. */
592
+ async #sendDrafts(entries) {
593
+ const drafts = entries.flatMap(({ threadId, number }) => {
594
+ const thread = this.#options.store.get(threadId);
595
+ return thread?.status === "draft" && thread.context && thread.pageUrl ? [{
596
+ thread,
597
+ number,
598
+ context: thread.context,
599
+ pageUrl: thread.pageUrl
600
+ }] : [];
601
+ });
602
+ if (drafts.length === 0) return;
603
+ const provider = this.#provider();
604
+ const attachments = [];
605
+ const comments = drafts.map(({ thread, number, context, pageUrl }) => {
606
+ const own = this.#draftAttachments.get(thread.id) ?? [];
607
+ const screenshots = own.map((_, index) => attachments.length + index + 1);
608
+ attachments.push(...own);
609
+ return {
610
+ number,
611
+ prompt: thread.messages[0]?.text ?? thread.title,
612
+ pageUrl,
613
+ context,
614
+ screenshots
615
+ };
616
+ });
617
+ const text = drafts.length === 1 ? renderPrompt({
618
+ ...comments[0],
619
+ hasScreenshot: attachments.length > 0
620
+ }) : renderBatchPrompt(comments);
621
+ const now = (/* @__PURE__ */ new Date()).toISOString();
622
+ const echo = localMessage(stripContext(text), now);
623
+ for (const { thread } of drafts) this.#update(thread.id, (current) => ({
624
+ ...current,
625
+ status: "starting",
626
+ messages: [echo],
627
+ provider: { id: provider.id }
628
+ }));
629
+ try {
630
+ const created = await provider.createThread({
631
+ title: drafts.length === 1 ? drafts[0].thread.title : batchTitle(drafts.map(({ thread }) => thread.title)),
632
+ text,
633
+ attachments,
634
+ model: this.#options.providers.modelFor(provider.id)
635
+ });
636
+ for (const { thread } of drafts) {
637
+ this.#draftAttachments.delete(thread.id);
638
+ this.#update(thread.id, (current) => ({
639
+ ...current,
640
+ status: "working",
641
+ provider: {
642
+ id: provider.id,
643
+ threadId: created.providerThreadId,
644
+ url: created.url
645
+ }
646
+ }));
647
+ }
648
+ this.#watch(provider.id, created.providerThreadId);
649
+ this.#options.log?.(`${drafts.length} queued pins → ${provider.label}`);
650
+ } catch (error) {
651
+ for (const { thread } of drafts) this.#update(thread.id, (current) => ({
652
+ ...current,
653
+ status: "draft",
654
+ statusDetail: error instanceof Error ? error.message : String(error),
655
+ messages: thread.messages
656
+ }));
657
+ throw error;
658
+ }
659
+ }
446
660
  /** Pin an element onto an existing provider thread: the prompt becomes its next message. */
447
661
  async #continue(message) {
448
662
  const { store } = this.#options;
@@ -593,9 +807,12 @@ var Bridge = class {
593
807
  }
594
808
  #settings() {
595
809
  const { providers } = this.#options;
810
+ const model = providers.modelFor(providers.defaultId);
596
811
  return {
597
812
  provider: providers.defaultId,
598
- providers: providers.choices
813
+ providers: providers.choices,
814
+ ...model ? { model } : {},
815
+ batch: providers.batch
599
816
  };
600
817
  }
601
818
  #require(threadId) {
@@ -666,6 +883,142 @@ function mergeMessage(thread, incoming) {
666
883
  };
667
884
  }
668
885
  //#endregion
886
+ //#region ../bridge/src/project-providers.ts
887
+ /**
888
+ * The providers of one project. New pins go to the project's default, which
889
+ * the overlay's settings change; existing pins keep the provider they were
890
+ * made with. Providers are created and started on first use.
891
+ */
892
+ var ProjectProviders = class ProjectProviders {
893
+ choices;
894
+ #options;
895
+ #providers = /* @__PURE__ */ new Map();
896
+ #listeners = /* @__PURE__ */ new Set();
897
+ #settingsListeners = /* @__PURE__ */ new Set();
898
+ #chosen;
899
+ #models = {};
900
+ /** On unless the project turns it off. */
901
+ #batch = true;
902
+ constructor(options) {
903
+ this.#options = options;
904
+ this.choices = options.choices;
905
+ }
906
+ /**
907
+ * Ready-made providers, the first being the default. Each is started
908
+ * here; `settings` keeps the project's picks (in memory when absent).
909
+ */
910
+ static of(providers, settings) {
911
+ const list = Array.isArray(providers) ? providers : [providers];
912
+ const [first] = list;
913
+ if (!first) throw new Error("ProjectProviders.of needs at least one provider");
914
+ const result = new ProjectProviders({
915
+ choices: list.map((provider) => ({
916
+ id: provider.id,
917
+ label: provider.label
918
+ })),
919
+ fallback: first.id,
920
+ create: (id) => list.find((provider) => provider.id === id) ?? first,
921
+ settings
922
+ });
923
+ for (const provider of list) result.get(provider.id);
924
+ return result;
925
+ }
926
+ async load() {
927
+ const saved = await this.#options.settings?.load();
928
+ if (saved) {
929
+ this.#chosen = saved.provider;
930
+ this.#models = saved.models ?? {};
931
+ this.#batch = saved.batch ?? true;
932
+ }
933
+ }
934
+ get defaultId() {
935
+ const chosen = this.#chosen;
936
+ return chosen && this.choices.some((choice) => choice.id === chosen) ? chosen : this.#options.fallback;
937
+ }
938
+ default() {
939
+ return this.get(this.defaultId);
940
+ }
941
+ /** Can pins of this provider be served (a choice, or one already running)? */
942
+ has(id) {
943
+ return this.#providers.has(id) || this.choices.some((choice) => choice.id === id);
944
+ }
945
+ get(id) {
946
+ let provider = this.#providers.get(id);
947
+ if (!provider) {
948
+ provider = this.#options.create(id);
949
+ this.#providers.set(id, provider);
950
+ if (provider.id !== id) this.#providers.set(provider.id, provider);
951
+ provider.start();
952
+ }
953
+ return provider;
954
+ }
955
+ async setDefault(id) {
956
+ if (!this.choices.some((choice) => choice.id === id)) throw new Error(`Unknown provider "${id}"`);
957
+ if (id === this.defaultId) return;
958
+ this.#chosen = id;
959
+ await this.#save();
960
+ for (const listener of this.#listeners) listener();
961
+ }
962
+ /** The model picked for a provider's new threads, if any. */
963
+ modelFor(id) {
964
+ return this.#models[id];
965
+ }
966
+ async setModel(id, model) {
967
+ if ((this.#models[id] ?? null) === model) return;
968
+ const { [id]: _previous, ...rest } = this.#models;
969
+ this.#models = model ? {
970
+ ...rest,
971
+ [id]: model
972
+ } : rest;
973
+ await this.#save();
974
+ for (const listener of this.#settingsListeners) listener();
975
+ }
976
+ get batch() {
977
+ return this.#batch;
978
+ }
979
+ async setBatch(on) {
980
+ if (on === this.#batch) return;
981
+ this.#batch = on;
982
+ await this.#save();
983
+ for (const listener of this.#settingsListeners) listener();
984
+ }
985
+ /** Fires when a picked model or batching changes. */
986
+ onSettingsChange(listener) {
987
+ this.#settingsListeners.add(listener);
988
+ return () => this.#settingsListeners.delete(listener);
989
+ }
990
+ onDefaultChange(listener) {
991
+ this.#listeners.add(listener);
992
+ return () => this.#listeners.delete(listener);
993
+ }
994
+ async dispose() {
995
+ await Promise.all([...new Set(this.#providers.values())].map((p) => p.dispose()));
996
+ this.#providers.clear();
997
+ }
998
+ async #save() {
999
+ await this.#options.settings?.save({
1000
+ provider: this.#chosen,
1001
+ models: this.#models,
1002
+ batch: this.#batch
1003
+ });
1004
+ }
1005
+ };
1006
+ //#endregion
1007
+ //#region ../bridge/src/thread-store.ts
1008
+ /**
1009
+ * A pin saved while its provider thread was still being created can't be
1010
+ * picked up again; stores apply this to pins they load from a previous run.
1011
+ * Everything else gets its real status from the provider once watched.
1012
+ */
1013
+ function settleInterrupted(thread) {
1014
+ if (thread.status !== "starting" || thread.provider.threadId) return thread;
1015
+ return {
1016
+ ...thread,
1017
+ status: "error",
1018
+ statusDetail: "Bridge stopped before the thread was created"
1019
+ };
1020
+ }
1021
+ //#endregion
669
1022
  //#region src/daemon/project-resolver.ts
670
1023
  const run$1 = promisify(execFile);
671
1024
  const defaultExec = async (command, args) => (await run$1(command, args, {
@@ -1619,6 +1972,66 @@ async function listT3Projects(options = {}) {
1619
1972
  }
1620
1973
  }
1621
1974
  //#endregion
1975
+ //#region ../provider-t3code/src/model-selection.ts
1976
+ /**
1977
+ * What a new thread runs on when nothing is picked, following T3 Code's
1978
+ * composer: the project's default, then the environment's default. T3 Code
1979
+ * otherwise reuses the model last used in that window, which only the window
1980
+ * knows, so the closest stand-in is the user's most recent thread in this
1981
+ * project. Without any of those: the first ready agent and its default model.
1982
+ */
1983
+ function resolveModelSelection(sources) {
1984
+ const { settings } = sources;
1985
+ const usable = usableProviders(sources.providers);
1986
+ const candidates = [
1987
+ settings?.projectSettingsFolded ? settings.projectSettingsOverrides?.[sources.projectId]?.defaultModelSelection : sources.projectDefault,
1988
+ settings?.defaultModelSelection,
1989
+ ...sources.recent
1990
+ ];
1991
+ for (const candidate of candidates) if (candidate && runsOn(usable, candidate)) return candidate;
1992
+ const provider = usable.find((p) => p.status === "ready") ?? usable[0];
1993
+ const model = provider?.models.find((m) => m.isDefault) ?? provider?.models[0];
1994
+ return provider && model ? {
1995
+ instanceId: provider.instanceId,
1996
+ model: model.slug
1997
+ } : void 0;
1998
+ }
1999
+ /** Every model of every agent that can start a thread, in T3 Code's order. */
2000
+ function modelOptions(providers) {
2001
+ return usableProviders(providers).flatMap((provider) => provider.models.map((model) => ({
2002
+ id: modelId({
2003
+ instanceId: provider.instanceId,
2004
+ model: model.slug
2005
+ }),
2006
+ label: model.name ?? model.slug,
2007
+ group: provider.displayName ?? provider.instanceId,
2008
+ agent: provider.driver ?? provider.instanceId
2009
+ })));
2010
+ }
2011
+ /** A picked model, if its agent can still start threads. */
2012
+ function pickedSelection(providers, id) {
2013
+ const selection = id ? parseModelId(id) : void 0;
2014
+ return selection && runsOn(usableProviders(providers), selection) ? selection : void 0;
2015
+ }
2016
+ /** Instance ids never contain a slash; model slugs may (`anthropic/claude-…`). */
2017
+ function modelId(selection) {
2018
+ return `${selection.instanceId}/${selection.model}`;
2019
+ }
2020
+ function parseModelId(id) {
2021
+ const slash = id.indexOf("/");
2022
+ if (slash <= 0 || slash === id.length - 1) return void 0;
2023
+ return {
2024
+ instanceId: id.slice(0, slash),
2025
+ model: id.slice(slash + 1)
2026
+ };
2027
+ }
2028
+ function usableProviders(providers) {
2029
+ return providers.filter((provider) => provider.enabled && provider.installed && provider.status !== "error" && provider.status !== "disabled");
2030
+ }
2031
+ function runsOn(usable, selection) {
2032
+ return Boolean(selection.model) && usable.some((p) => p.instanceId === selection.instanceId);
2033
+ }
2034
+ //#endregion
1622
2035
  //#region ../provider-t3code/src/protocols/adapter.ts
1623
2036
  function decodedSize(dataUrl) {
1624
2037
  return Buffer.from(dataUrl.split(",", 2)[1] ?? "", "base64").byteLength;
@@ -2312,6 +2725,29 @@ var T3CodeProvider = class {
2312
2725
  connection.drivers = new Map(config.providers.map((provider) => [provider.instanceId, provider.driver ?? provider.instanceId]));
2313
2726
  return connection.drivers;
2314
2727
  }
2728
+ /** Everything that decides a new thread's model, read fresh: settings change while we run. */
2729
+ async #modelSources(connection) {
2730
+ const [config, shell] = await Promise.all([connection.socket.request("server.getConfig", {}), this.#fetchJson("/api/orchestration/shell", connection.token)]);
2731
+ const { id } = connection.project;
2732
+ const project = shell.projects.find((candidate) => candidate.id === id);
2733
+ const recent = shell.threads.filter((thread) => thread.projectId === id && !this.#watchers.has(thread.id)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).flatMap(({ modelSelection: selection }) => {
2734
+ const instanceId = selection?.instanceId ?? selection?.provider;
2735
+ if (!instanceId || !selection?.model) return [];
2736
+ const { model, options } = selection;
2737
+ return [{
2738
+ instanceId,
2739
+ model,
2740
+ ...options ? { options } : {}
2741
+ }];
2742
+ });
2743
+ return {
2744
+ providers: config.providers,
2745
+ settings: config.settings,
2746
+ projectId: id,
2747
+ projectDefault: (project ?? connection.project).defaultModelSelection,
2748
+ recent
2749
+ };
2750
+ }
2315
2751
  /** Name like `owner/repo` and the project icon, matching T3 Code's sidebar. */
2316
2752
  async #projectPresentation(connection) {
2317
2753
  const { project } = connection;
@@ -2343,16 +2779,29 @@ var T3CodeProvider = class {
2343
2779
  threadUrl(providerThreadId) {
2344
2780
  return this.#connection ? this.#threadUrl(this.#connection, providerThreadId) : void 0;
2345
2781
  }
2782
+ async listModels() {
2783
+ const connection = this.#requireConnection();
2784
+ const sources = await this.#modelSources(connection);
2785
+ const fallback = this.#options.modelSelection ?? resolveModelSelection(sources);
2786
+ return {
2787
+ models: modelOptions(sources.providers),
2788
+ ...fallback ? { defaultModel: modelId(fallback) } : {}
2789
+ };
2790
+ }
2346
2791
  async createThread(input) {
2347
2792
  const connection = this.#requireConnection();
2793
+ const sources = await this.#modelSources(connection);
2794
+ const modelSelection = pickedSelection(sources.providers, input.model) ?? this.#options.modelSelection ?? resolveModelSelection(sources);
2795
+ if (!modelSelection) throw new Error("T3 Code has no usable provider. Set one up in T3 Code → Settings → Providers.");
2348
2796
  const threadId = randomUUID();
2797
+ this.#log(`New thread on ${modelId(modelSelection)}`);
2349
2798
  await connection.protocol.startThread(connection.socket, {
2350
2799
  threadId,
2351
2800
  projectId: connection.project.id,
2352
2801
  title: input.title,
2353
2802
  text: input.text,
2354
2803
  attachments: input.attachments,
2355
- modelSelection: connection.modelSelection,
2804
+ modelSelection,
2356
2805
  runtimeMode: this.#runtimeMode(),
2357
2806
  interactionMode: this.#options.interactionMode ?? "default"
2358
2807
  });
@@ -2412,7 +2861,7 @@ var T3CodeProvider = class {
2412
2861
  state: "ready",
2413
2862
  target: connection.project.title
2414
2863
  });
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}`);
2864
+ this.#log(`Connected to T3 Code at ${this.#baseUrl} · project "${connection.project.title}" · protocol v${connection.protocol.version}`);
2416
2865
  for (const [threadId, watcher] of this.#watchers) this.#subscribe(connection, threadId, watcher);
2417
2866
  } catch (error) {
2418
2867
  unauthorized = error instanceof UnauthorizedError;
@@ -2453,7 +2902,6 @@ var T3CodeProvider = class {
2453
2902
  socket.requestTimeoutMs = this.#timeouts.rpcMs;
2454
2903
  try {
2455
2904
  const project = await this.#resolveProject(socket, protocol, token);
2456
- const modelSelection = this.#options.modelSelection ?? project.defaultModelSelection ?? await this.#defaultModelSelection(socket);
2457
2905
  socket.onClose((reason) => {
2458
2906
  if (this.#connection?.socket !== socket) return;
2459
2907
  this.#connection = void 0;
@@ -2469,8 +2917,7 @@ var T3CodeProvider = class {
2469
2917
  socket,
2470
2918
  protocol,
2471
2919
  environmentId: environment.environmentId,
2472
- project,
2473
- modelSelection
2920
+ project
2474
2921
  };
2475
2922
  } catch (error) {
2476
2923
  socket.close();
@@ -2516,16 +2963,6 @@ var T3CodeProvider = class {
2516
2963
  this.#hadProject = true;
2517
2964
  return project;
2518
2965
  }
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
2966
  #subscribe(connection, threadId, watcher) {
2530
2967
  watcher.cancel?.();
2531
2968
  watcher.tracker = connection.protocol.createTracker();
@@ -2608,7 +3045,7 @@ function errorMessage(error) {
2608
3045
  }
2609
3046
  //#endregion
2610
3047
  //#region src/version.ts
2611
- const VERSION = "0.3.2";
3048
+ const VERSION = "0.5.0";
2612
3049
  //#endregion
2613
3050
  //#region src/daemon/thread-store.ts
2614
3051
  const StoreFile = z.object({
@@ -2636,7 +3073,7 @@ function projectStorePath(projectRoot, dataDir = defaultDataDir()) {
2636
3073
  * Pins for one project, persisted outside the repo so they survive bridge
2637
3074
  * restarts without leaving files in the project. Writes are debounced and atomic.
2638
3075
  */
2639
- var ThreadStore = class {
3076
+ var FileThreadStore = class {
2640
3077
  path;
2641
3078
  #root;
2642
3079
  #threads = /* @__PURE__ */ new Map();
@@ -2651,13 +3088,7 @@ var ThreadStore = class {
2651
3088
  if (raw === void 0) return;
2652
3089
  const parsed = StoreFile.safeParse(JSON.parse(raw));
2653
3090
  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
- }
3091
+ for (const thread of parsed.data.threads) this.#threads.set(thread.id, settleInterrupted(thread));
2661
3092
  }
2662
3093
  list() {
2663
3094
  return [...this.#threads.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -2778,92 +3209,41 @@ async function hasClaudeCode() {
2778
3209
  return (await Promise.all(candidates.map((path) => access(path).then(() => true, () => false)))).includes(true);
2779
3210
  }
2780
3211
  //#endregion
2781
- //#region src/daemon/project-providers.ts
3212
+ //#region src/daemon/project-settings.ts
2782
3213
  const SettingsFile = z.object({
2783
3214
  version: z.literal(1),
2784
3215
  /** The provider new pins go to; unset means the daemon's `--provider`. */
2785
- provider: z.string().optional()
3216
+ provider: z.string().optional(),
3217
+ /** Model picked per provider for new threads; unset means the provider's default. */
3218
+ models: z.record(z.string(), z.string()).optional(),
3219
+ /** Queue new comments and send them together. */
3220
+ batch: z.boolean().optional()
2786
3221
  });
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;
3222
+ /** A project's settings live next to its pins: `<slug>-<hash>.settings.json`. */
3223
+ function projectSettingsPath(projectRoot, dataDir = defaultDataDir()) {
3224
+ return projectStorePath(projectRoot, dataDir).replace(/\.json$/, ".settings.json");
3225
+ }
3226
+ /** A project's overlay settings (provider, models, batching) in a JSON file. */
3227
+ var FileProjectSettings = class {
3228
+ path;
3229
+ constructor(path) {
3230
+ this.path = path;
2814
3231
  }
2815
3232
  async load() {
2816
- if (!this.#options.settingsPath) return;
2817
- const raw = await readFile(this.#options.settingsPath, "utf8").catch(() => void 0);
3233
+ const raw = await readFile(this.path, "utf8").catch(() => void 0);
2818
3234
  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);
3235
+ return parsed?.success ? parsed.data : void 0;
2827
3236
  }
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`;
3237
+ async save(settings) {
3238
+ await mkdir(dirname(this.path), { recursive: true });
3239
+ const temp = `${this.path}.tmp`;
2862
3240
  await writeFile(temp, `${JSON.stringify({
2863
3241
  version: 1,
2864
- provider: this.#chosen
3242
+ provider: settings.provider,
3243
+ models: settings.models,
3244
+ batch: settings.batch
2865
3245
  }, null, 2)}\n`);
2866
- await rename(temp, path);
3246
+ await rename(temp, this.path);
2867
3247
  }
2868
3248
  };
2869
3249
  //#endregion
@@ -2976,9 +3356,9 @@ async function startDaemon(options = {}) {
2976
3356
  t3Url
2977
3357
  }),
2978
3358
  create: (id) => createProvider(key, id),
2979
- settingsPath: projectStorePath(key, dataDir).replace(/\.json$/, ".settings.json")
3359
+ settings: new FileProjectSettings(projectSettingsPath(key, dataDir))
2980
3360
  });
2981
- const store = new ThreadStore(key, dataDir);
3361
+ const store = new FileThreadStore(key, dataDir);
2982
3362
  await Promise.all([store.load(), providers.load()]);
2983
3363
  const bridge = new Bridge({
2984
3364
  providers,
@@ -3202,4 +3582,4 @@ function resolveOverlayPath() {
3202
3582
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
3203
3583
  }
3204
3584
  //#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 };
3585
+ 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, FileThreadStore 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 };