tencil 0.3.2 → 0.4.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.
@@ -80,7 +80,22 @@ const ClientMessage = z.discriminatedUnion("type", [
80
80
  context: ElementContext,
81
81
  attachments: z.array(ImageAttachment).max(4).default([]),
82
82
  /** Continue this existing provider thread instead of starting a new one. */
83
- providerThreadId: z.string().optional()
83
+ providerThreadId: z.string().optional(),
84
+ /** Queue it for a batch (`drafts.send`) instead of sending it now. */
85
+ draft: z.boolean().optional()
86
+ }),
87
+ z.object({
88
+ type: z.literal("thread.edit"),
89
+ threadId: z.string(),
90
+ prompt: z.string().min(1)
91
+ }),
92
+ z.object({
93
+ type: z.literal("drafts.send"),
94
+ /** In pin order; `number` is the pin's number, which the agent refers to. */
95
+ drafts: z.array(z.object({
96
+ threadId: z.string(),
97
+ number: z.number().int().positive()
98
+ })).min(1)
84
99
  }),
85
100
  z.object({
86
101
  type: z.literal("thread.open"),
@@ -89,6 +104,7 @@ const ClientMessage = z.discriminatedUnion("type", [
89
104
  title: z.string().optional()
90
105
  }),
91
106
  z.object({ type: z.literal("provider.threads") }),
107
+ z.object({ type: z.literal("provider.models") }),
92
108
  z.object({
93
109
  type: z.literal("project.select"),
94
110
  root: z.string().min(1)
@@ -113,9 +129,19 @@ const ClientMessage = z.discriminatedUnion("type", [
113
129
  type: z.literal("thread.delete"),
114
130
  threadId: z.string()
115
131
  }),
132
+ z.object({
133
+ type: z.literal("thread.move"),
134
+ threadId: z.string(),
135
+ anchor: Anchor
136
+ }),
116
137
  z.object({
117
138
  type: z.literal("settings.update"),
118
- provider: z.string().min(1)
139
+ provider: z.string().min(1).optional(),
140
+ batch: z.boolean().optional()
141
+ }),
142
+ z.object({
143
+ type: z.literal("model.select"),
144
+ model: z.string().min(1).nullable()
119
145
  })
120
146
  ]);
121
147
  z.object({
@@ -141,12 +167,17 @@ const ProviderOption = z.object({
141
167
  z.object({
142
168
  /** Provider new pins go to; existing pins keep their own. */
143
169
  provider: z.string(),
144
- providers: z.array(ProviderOption)
170
+ providers: z.array(ProviderOption),
171
+ /** Model picked for the provider's new threads; unset means the provider's default. */
172
+ model: z.string().optional(),
173
+ /** New comments are queued and sent together. */
174
+ batch: z.boolean()
145
175
  });
146
176
  //#endregion
147
177
  //#region ../protocol/src/thread.ts
148
178
  /**
149
179
  * Provider-agnostic run state.
180
+ * - `draft`: a comment queued in a batch, not sent to the agent yet
150
181
  * - `starting`: thread is being created on the provider
151
182
  * - `working`: the agent is producing a turn
152
183
  * - `waiting`: the agent needs approval/input inside the provider UI
@@ -154,6 +185,7 @@ z.object({
154
185
  * - `error`: last turn or the thread itself failed
155
186
  */
156
187
  const ThreadStatus = z.enum([
188
+ "draft",
157
189
  "starting",
158
190
  "working",
159
191
  "waiting",
@@ -219,6 +251,15 @@ z.object({
219
251
  /** Agent driver, e.g. `codex` or `claudeAgent`, for the provider icon. */
220
252
  agent: z.string().optional()
221
253
  });
254
+ z.object({
255
+ /** Opaque to the overlay; the provider parses it back. */
256
+ id: z.string(),
257
+ label: z.string(),
258
+ /** The agent it belongs to, e.g. "Claude" or "Codex". */
259
+ group: z.string(),
260
+ /** Agent kind for its icon (`codex`, `claudeAgent`). */
261
+ agent: z.string().optional()
262
+ });
222
263
  z.object({
223
264
  name: z.string(),
224
265
  /** Absolute URL of the project's favicon, if it has one. */
@@ -226,7 +267,7 @@ z.object({
226
267
  emoji: z.string().optional()
227
268
  });
228
269
  //#endregion
229
- //#region src/daemon/prompt.ts
270
+ //#region ../bridge/src/prompt.ts
230
271
  const CONTEXT_OPEN = "<tencil-context>";
231
272
  const CONTEXT_CLOSE = "</tencil-context>";
232
273
  /**
@@ -235,13 +276,29 @@ const CONTEXT_CLOSE = "</tencil-context>";
235
276
  * shown in the overlay (`stripContext`).
236
277
  */
237
278
  function renderPrompt(input) {
238
- const { context } = input;
239
279
  const lines = [
240
280
  "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
281
  "",
242
- `- Page: ${input.pageUrl}`,
243
- `- Element: \`${oneLine(context.html)}\``
282
+ ...contextLines(input.pageUrl, input.context)
244
283
  ];
284
+ if (input.hasScreenshot) lines.push("- A screenshot of the element is attached.");
285
+ return `${input.prompt.trim()}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
286
+ }
287
+ /**
288
+ * Several queued comments as one message: the comments first, numbered like
289
+ * their pins, then one context block with a section per comment. Stripping
290
+ * the block leaves the numbered comments.
291
+ */
292
+ function renderBatchPrompt(comments) {
293
+ 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.`];
294
+ for (const comment of comments) {
295
+ lines.push("", `#${comment.number}`, ...contextLines(comment.pageUrl, comment.context));
296
+ if (comment.screenshots.length > 0) lines.push(`- Screenshot: attached image ${comment.screenshots.join(", ")}`);
297
+ }
298
+ return `${comments.map((comment) => `#${comment.number} ${comment.prompt.trim()}`).join("\n\n")}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
299
+ }
300
+ function contextLines(pageUrl, context) {
301
+ const lines = [`- Page: ${pageUrl}`, `- Element: \`${oneLine(context.html)}\``];
245
302
  const [component, ...owners] = context.components;
246
303
  if (component) {
247
304
  const chain = [component, ...owners.slice(0, 4)].map(formatFrame).join(" ← ");
@@ -252,8 +309,7 @@ function renderPrompt(input) {
252
309
  if (context.selection) lines.push(`- Selected text: "${truncate(oneLine(context.selection), 300)}"`);
253
310
  const { rect, viewport } = context;
254
311
  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}`;
312
+ return lines;
257
313
  }
258
314
  function stripContext(text) {
259
315
  const index = text.indexOf(CONTEXT_OPEN);
@@ -263,6 +319,9 @@ function titleFor(prompt, context) {
263
319
  const firstLine = prompt.trim().split("\n", 1)[0] ?? "";
264
320
  return truncate(`${context.components[0]?.name ?? `<${context.tagName}>`}: ${firstLine}`, 80);
265
321
  }
322
+ function batchTitle(titles) {
323
+ return truncate(`${titles.length} comments: ${titles.join(" · ")}`, 80);
324
+ }
266
325
  function formatFrame(frame) {
267
326
  if (frame.library) return `${frame.name} (${frame.library})`;
268
327
  if (!frame.source) return frame.name;
@@ -276,7 +335,7 @@ function truncate(text, max) {
276
335
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
277
336
  }
278
337
  //#endregion
279
- //#region src/daemon/bridge.ts
338
+ //#region ../bridge/src/bridge.ts
280
339
  /** Local echo ids, replaced once the provider reports the real user message. */
281
340
  const LOCAL_PREFIX = "local:";
282
341
  const BROADCAST_THROTTLE_MS = 80;
@@ -290,8 +349,11 @@ var Bridge = class {
290
349
  /** One provider subscription per provider thread, shared by every pin bound to it. */
291
350
  #watches = /* @__PURE__ */ new Map();
292
351
  #pendingBroadcast = /* @__PURE__ */ new Map();
352
+ /** Screenshots of queued comments, kept in memory until the batch is sent. */
353
+ #draftAttachments = /* @__PURE__ */ new Map();
293
354
  #offInfo = () => {};
294
355
  #offDefault;
356
+ #offSettings;
295
357
  constructor(options) {
296
358
  this.#options = options;
297
359
  this.#followDefault();
@@ -306,6 +368,10 @@ var Bridge = class {
306
368
  provider: this.#provider().info()
307
369
  });
308
370
  });
371
+ this.#offSettings = options.providers.onSettingsChange(() => this.#broadcast({
372
+ type: "settings",
373
+ settings: this.#settings()
374
+ }));
309
375
  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
376
  }
311
377
  connect(client) {
@@ -336,7 +402,26 @@ var Bridge = class {
336
402
  });
337
403
  return;
338
404
  case "thread.create":
339
- await (message.providerThreadId ? this.#continue(message) : this.#create(message));
405
+ if (message.draft) this.#queue(message);
406
+ else if (message.providerThreadId) await this.#continue(message);
407
+ else await this.#create(message);
408
+ return;
409
+ case "thread.edit": {
410
+ const draft = this.#require(message.threadId);
411
+ if (draft.status !== "draft") throw new Error("Only queued comments can be edited");
412
+ const [first] = draft.messages;
413
+ this.#update(draft.id, (thread) => ({
414
+ ...thread,
415
+ title: thread.context ? titleFor(message.prompt, thread.context) : message.prompt,
416
+ messages: first ? [{
417
+ ...first,
418
+ text: message.prompt
419
+ }] : []
420
+ }));
421
+ return;
422
+ }
423
+ case "drafts.send":
424
+ await this.#sendDrafts(message.drafts);
340
425
  return;
341
426
  case "thread.open":
342
427
  this.#open(message);
@@ -350,9 +435,26 @@ var Bridge = class {
350
435
  ...await this.#provider().listThreads()
351
436
  });
352
437
  return;
353
- case "settings.update":
354
- await this.#options.providers.setDefault(message.provider);
438
+ case "settings.update": {
439
+ const { providers } = this.#options;
440
+ if (message.provider) await providers.setDefault(message.provider);
441
+ if (message.batch !== void 0) await providers.setBatch(message.batch);
355
442
  return;
443
+ }
444
+ case "provider.models": {
445
+ const provider = this.#provider();
446
+ client.send({
447
+ type: "provider.models",
448
+ provider: provider.id,
449
+ ...await provider.listModels?.() ?? { models: [] }
450
+ });
451
+ return;
452
+ }
453
+ case "model.select": {
454
+ const { providers } = this.#options;
455
+ await providers.setModel(providers.defaultId, message.model);
456
+ return;
457
+ }
356
458
  case "thread.reply":
357
459
  await this.#reply(message);
358
460
  return;
@@ -367,8 +469,15 @@ var Bridge = class {
367
469
  resolved: message.resolved
368
470
  }));
369
471
  return;
472
+ case "thread.move":
473
+ this.#update(message.threadId, (thread) => ({
474
+ ...thread,
475
+ anchor: message.anchor
476
+ }));
477
+ return;
370
478
  case "thread.delete": {
371
479
  const provider = this.#options.store.get(message.threadId)?.provider;
480
+ this.#draftAttachments.delete(message.threadId);
372
481
  if (this.#options.store.delete(message.threadId)) this.#broadcast({
373
482
  type: "thread.removed",
374
483
  threadId: message.threadId
@@ -389,6 +498,7 @@ var Bridge = class {
389
498
  async dispose() {
390
499
  this.#offInfo();
391
500
  this.#offDefault();
501
+ this.#offSettings();
392
502
  for (const unwatch of this.#watches.values()) unwatch();
393
503
  for (const timer of this.#pendingBroadcast.values()) clearTimeout(timer);
394
504
  await this.#options.store.flush();
@@ -422,7 +532,8 @@ var Bridge = class {
422
532
  context: message.context,
423
533
  hasScreenshot: message.attachments.length > 0
424
534
  }),
425
- attachments: message.attachments
535
+ attachments: message.attachments,
536
+ model: this.#options.providers.modelFor(provider.id)
426
537
  });
427
538
  this.#update(thread.id, (current) => ({
428
539
  ...current,
@@ -443,6 +554,96 @@ var Bridge = class {
443
554
  }));
444
555
  }
445
556
  }
557
+ /** Pin a comment without sending it: it waits for `drafts.send`. */
558
+ #queue(message) {
559
+ const { store } = this.#options;
560
+ if (store.get(message.id)) throw new Error(`Thread ${message.id} already exists`);
561
+ const now = (/* @__PURE__ */ new Date()).toISOString();
562
+ store.upsert({
563
+ id: message.id,
564
+ title: titleFor(message.prompt, message.context),
565
+ pageUrl: message.pageUrl,
566
+ anchor: message.anchor,
567
+ context: message.context,
568
+ status: "draft",
569
+ resolved: false,
570
+ messages: [localMessage(message.prompt, now)],
571
+ provider: { id: this.#provider().id },
572
+ createdAt: now,
573
+ updatedAt: now
574
+ });
575
+ if (message.attachments.length > 0) this.#draftAttachments.set(message.id, message.attachments);
576
+ this.#broadcastThread(store.get(message.id), true);
577
+ }
578
+ /** Queued comments go out together: one message, one new provider thread, shared by their pins. */
579
+ async #sendDrafts(entries) {
580
+ const drafts = entries.flatMap(({ threadId, number }) => {
581
+ const thread = this.#options.store.get(threadId);
582
+ return thread?.status === "draft" && thread.context && thread.pageUrl ? [{
583
+ thread,
584
+ number,
585
+ context: thread.context,
586
+ pageUrl: thread.pageUrl
587
+ }] : [];
588
+ });
589
+ if (drafts.length === 0) return;
590
+ const provider = this.#provider();
591
+ const attachments = [];
592
+ const comments = drafts.map(({ thread, number, context, pageUrl }) => {
593
+ const own = this.#draftAttachments.get(thread.id) ?? [];
594
+ const screenshots = own.map((_, index) => attachments.length + index + 1);
595
+ attachments.push(...own);
596
+ return {
597
+ number,
598
+ prompt: thread.messages[0]?.text ?? thread.title,
599
+ pageUrl,
600
+ context,
601
+ screenshots
602
+ };
603
+ });
604
+ const text = drafts.length === 1 ? renderPrompt({
605
+ ...comments[0],
606
+ hasScreenshot: attachments.length > 0
607
+ }) : renderBatchPrompt(comments);
608
+ const now = (/* @__PURE__ */ new Date()).toISOString();
609
+ const echo = localMessage(stripContext(text), now);
610
+ for (const { thread } of drafts) this.#update(thread.id, (current) => ({
611
+ ...current,
612
+ status: "starting",
613
+ messages: [echo],
614
+ provider: { id: provider.id }
615
+ }));
616
+ try {
617
+ const created = await provider.createThread({
618
+ title: drafts.length === 1 ? drafts[0].thread.title : batchTitle(drafts.map(({ thread }) => thread.title)),
619
+ text,
620
+ attachments,
621
+ model: this.#options.providers.modelFor(provider.id)
622
+ });
623
+ for (const { thread } of drafts) {
624
+ this.#draftAttachments.delete(thread.id);
625
+ this.#update(thread.id, (current) => ({
626
+ ...current,
627
+ status: "working",
628
+ provider: {
629
+ id: provider.id,
630
+ threadId: created.providerThreadId,
631
+ url: created.url
632
+ }
633
+ }));
634
+ }
635
+ this.#watch(provider.id, created.providerThreadId);
636
+ this.#options.log?.(`${drafts.length} queued pins → ${provider.label}`);
637
+ } catch (error) {
638
+ for (const { thread } of drafts) this.#update(thread.id, (current) => ({
639
+ ...current,
640
+ status: "draft",
641
+ statusDetail: error instanceof Error ? error.message : String(error),
642
+ messages: thread.messages
643
+ }));
644
+ throw error;
645
+ }
646
+ }
446
647
  /** Pin an element onto an existing provider thread: the prompt becomes its next message. */
447
648
  async #continue(message) {
448
649
  const { store } = this.#options;
@@ -593,9 +794,12 @@ var Bridge = class {
593
794
  }
594
795
  #settings() {
595
796
  const { providers } = this.#options;
797
+ const model = providers.modelFor(providers.defaultId);
596
798
  return {
597
799
  provider: providers.defaultId,
598
- providers: providers.choices
800
+ providers: providers.choices,
801
+ ...model ? { model } : {},
802
+ batch: providers.batch
599
803
  };
600
804
  }
601
805
  #require(threadId) {
@@ -666,6 +870,142 @@ function mergeMessage(thread, incoming) {
666
870
  };
667
871
  }
668
872
  //#endregion
873
+ //#region ../bridge/src/project-providers.ts
874
+ /**
875
+ * The providers of one project. New pins go to the project's default, which
876
+ * the overlay's settings change; existing pins keep the provider they were
877
+ * made with. Providers are created and started on first use.
878
+ */
879
+ var ProjectProviders = class ProjectProviders {
880
+ choices;
881
+ #options;
882
+ #providers = /* @__PURE__ */ new Map();
883
+ #listeners = /* @__PURE__ */ new Set();
884
+ #settingsListeners = /* @__PURE__ */ new Set();
885
+ #chosen;
886
+ #models = {};
887
+ /** On unless the project turns it off. */
888
+ #batch = true;
889
+ constructor(options) {
890
+ this.#options = options;
891
+ this.choices = options.choices;
892
+ }
893
+ /**
894
+ * Ready-made providers, the first being the default. Each is started
895
+ * here; `settings` keeps the project's picks (in memory when absent).
896
+ */
897
+ static of(providers, settings) {
898
+ const list = Array.isArray(providers) ? providers : [providers];
899
+ const [first] = list;
900
+ if (!first) throw new Error("ProjectProviders.of needs at least one provider");
901
+ const result = new ProjectProviders({
902
+ choices: list.map((provider) => ({
903
+ id: provider.id,
904
+ label: provider.label
905
+ })),
906
+ fallback: first.id,
907
+ create: (id) => list.find((provider) => provider.id === id) ?? first,
908
+ settings
909
+ });
910
+ for (const provider of list) result.get(provider.id);
911
+ return result;
912
+ }
913
+ async load() {
914
+ const saved = await this.#options.settings?.load();
915
+ if (saved) {
916
+ this.#chosen = saved.provider;
917
+ this.#models = saved.models ?? {};
918
+ this.#batch = saved.batch ?? true;
919
+ }
920
+ }
921
+ get defaultId() {
922
+ const chosen = this.#chosen;
923
+ return chosen && this.choices.some((choice) => choice.id === chosen) ? chosen : this.#options.fallback;
924
+ }
925
+ default() {
926
+ return this.get(this.defaultId);
927
+ }
928
+ /** Can pins of this provider be served (a choice, or one already running)? */
929
+ has(id) {
930
+ return this.#providers.has(id) || this.choices.some((choice) => choice.id === id);
931
+ }
932
+ get(id) {
933
+ let provider = this.#providers.get(id);
934
+ if (!provider) {
935
+ provider = this.#options.create(id);
936
+ this.#providers.set(id, provider);
937
+ if (provider.id !== id) this.#providers.set(provider.id, provider);
938
+ provider.start();
939
+ }
940
+ return provider;
941
+ }
942
+ async setDefault(id) {
943
+ if (!this.choices.some((choice) => choice.id === id)) throw new Error(`Unknown provider "${id}"`);
944
+ if (id === this.defaultId) return;
945
+ this.#chosen = id;
946
+ await this.#save();
947
+ for (const listener of this.#listeners) listener();
948
+ }
949
+ /** The model picked for a provider's new threads, if any. */
950
+ modelFor(id) {
951
+ return this.#models[id];
952
+ }
953
+ async setModel(id, model) {
954
+ if ((this.#models[id] ?? null) === model) return;
955
+ const { [id]: _previous, ...rest } = this.#models;
956
+ this.#models = model ? {
957
+ ...rest,
958
+ [id]: model
959
+ } : rest;
960
+ await this.#save();
961
+ for (const listener of this.#settingsListeners) listener();
962
+ }
963
+ get batch() {
964
+ return this.#batch;
965
+ }
966
+ async setBatch(on) {
967
+ if (on === this.#batch) return;
968
+ this.#batch = on;
969
+ await this.#save();
970
+ for (const listener of this.#settingsListeners) listener();
971
+ }
972
+ /** Fires when a picked model or batching changes. */
973
+ onSettingsChange(listener) {
974
+ this.#settingsListeners.add(listener);
975
+ return () => this.#settingsListeners.delete(listener);
976
+ }
977
+ onDefaultChange(listener) {
978
+ this.#listeners.add(listener);
979
+ return () => this.#listeners.delete(listener);
980
+ }
981
+ async dispose() {
982
+ await Promise.all([...new Set(this.#providers.values())].map((p) => p.dispose()));
983
+ this.#providers.clear();
984
+ }
985
+ async #save() {
986
+ await this.#options.settings?.save({
987
+ provider: this.#chosen,
988
+ models: this.#models,
989
+ batch: this.#batch
990
+ });
991
+ }
992
+ };
993
+ //#endregion
994
+ //#region ../bridge/src/thread-store.ts
995
+ /**
996
+ * A pin saved while its provider thread was still being created can't be
997
+ * picked up again; stores apply this to pins they load from a previous run.
998
+ * Everything else gets its real status from the provider once watched.
999
+ */
1000
+ function settleInterrupted(thread) {
1001
+ if (thread.status !== "starting" || thread.provider.threadId) return thread;
1002
+ return {
1003
+ ...thread,
1004
+ status: "error",
1005
+ statusDetail: "Bridge stopped before the thread was created"
1006
+ };
1007
+ }
1008
+ //#endregion
669
1009
  //#region src/daemon/project-resolver.ts
670
1010
  const run$1 = promisify(execFile);
671
1011
  const defaultExec = async (command, args) => (await run$1(command, args, {
@@ -1619,6 +1959,66 @@ async function listT3Projects(options = {}) {
1619
1959
  }
1620
1960
  }
1621
1961
  //#endregion
1962
+ //#region ../provider-t3code/src/model-selection.ts
1963
+ /**
1964
+ * What a new thread runs on when nothing is picked, following T3 Code's
1965
+ * composer: the project's default, then the environment's default. T3 Code
1966
+ * otherwise reuses the model last used in that window, which only the window
1967
+ * knows, so the closest stand-in is the user's most recent thread in this
1968
+ * project. Without any of those: the first ready agent and its default model.
1969
+ */
1970
+ function resolveModelSelection(sources) {
1971
+ const { settings } = sources;
1972
+ const usable = usableProviders(sources.providers);
1973
+ const candidates = [
1974
+ settings?.projectSettingsFolded ? settings.projectSettingsOverrides?.[sources.projectId]?.defaultModelSelection : sources.projectDefault,
1975
+ settings?.defaultModelSelection,
1976
+ ...sources.recent
1977
+ ];
1978
+ for (const candidate of candidates) if (candidate && runsOn(usable, candidate)) return candidate;
1979
+ const provider = usable.find((p) => p.status === "ready") ?? usable[0];
1980
+ const model = provider?.models.find((m) => m.isDefault) ?? provider?.models[0];
1981
+ return provider && model ? {
1982
+ instanceId: provider.instanceId,
1983
+ model: model.slug
1984
+ } : void 0;
1985
+ }
1986
+ /** Every model of every agent that can start a thread, in T3 Code's order. */
1987
+ function modelOptions(providers) {
1988
+ return usableProviders(providers).flatMap((provider) => provider.models.map((model) => ({
1989
+ id: modelId({
1990
+ instanceId: provider.instanceId,
1991
+ model: model.slug
1992
+ }),
1993
+ label: model.name ?? model.slug,
1994
+ group: provider.displayName ?? provider.instanceId,
1995
+ agent: provider.driver ?? provider.instanceId
1996
+ })));
1997
+ }
1998
+ /** A picked model, if its agent can still start threads. */
1999
+ function pickedSelection(providers, id) {
2000
+ const selection = id ? parseModelId(id) : void 0;
2001
+ return selection && runsOn(usableProviders(providers), selection) ? selection : void 0;
2002
+ }
2003
+ /** Instance ids never contain a slash; model slugs may (`anthropic/claude-…`). */
2004
+ function modelId(selection) {
2005
+ return `${selection.instanceId}/${selection.model}`;
2006
+ }
2007
+ function parseModelId(id) {
2008
+ const slash = id.indexOf("/");
2009
+ if (slash <= 0 || slash === id.length - 1) return void 0;
2010
+ return {
2011
+ instanceId: id.slice(0, slash),
2012
+ model: id.slice(slash + 1)
2013
+ };
2014
+ }
2015
+ function usableProviders(providers) {
2016
+ return providers.filter((provider) => provider.enabled && provider.installed && provider.status !== "error" && provider.status !== "disabled");
2017
+ }
2018
+ function runsOn(usable, selection) {
2019
+ return Boolean(selection.model) && usable.some((p) => p.instanceId === selection.instanceId);
2020
+ }
2021
+ //#endregion
1622
2022
  //#region ../provider-t3code/src/protocols/adapter.ts
1623
2023
  function decodedSize(dataUrl) {
1624
2024
  return Buffer.from(dataUrl.split(",", 2)[1] ?? "", "base64").byteLength;
@@ -2312,6 +2712,29 @@ var T3CodeProvider = class {
2312
2712
  connection.drivers = new Map(config.providers.map((provider) => [provider.instanceId, provider.driver ?? provider.instanceId]));
2313
2713
  return connection.drivers;
2314
2714
  }
2715
+ /** Everything that decides a new thread's model, read fresh: settings change while we run. */
2716
+ async #modelSources(connection) {
2717
+ const [config, shell] = await Promise.all([connection.socket.request("server.getConfig", {}), this.#fetchJson("/api/orchestration/shell", connection.token)]);
2718
+ const { id } = connection.project;
2719
+ const project = shell.projects.find((candidate) => candidate.id === id);
2720
+ 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 }) => {
2721
+ const instanceId = selection?.instanceId ?? selection?.provider;
2722
+ if (!instanceId || !selection?.model) return [];
2723
+ const { model, options } = selection;
2724
+ return [{
2725
+ instanceId,
2726
+ model,
2727
+ ...options ? { options } : {}
2728
+ }];
2729
+ });
2730
+ return {
2731
+ providers: config.providers,
2732
+ settings: config.settings,
2733
+ projectId: id,
2734
+ projectDefault: (project ?? connection.project).defaultModelSelection,
2735
+ recent
2736
+ };
2737
+ }
2315
2738
  /** Name like `owner/repo` and the project icon, matching T3 Code's sidebar. */
2316
2739
  async #projectPresentation(connection) {
2317
2740
  const { project } = connection;
@@ -2343,16 +2766,29 @@ var T3CodeProvider = class {
2343
2766
  threadUrl(providerThreadId) {
2344
2767
  return this.#connection ? this.#threadUrl(this.#connection, providerThreadId) : void 0;
2345
2768
  }
2769
+ async listModels() {
2770
+ const connection = this.#requireConnection();
2771
+ const sources = await this.#modelSources(connection);
2772
+ const fallback = this.#options.modelSelection ?? resolveModelSelection(sources);
2773
+ return {
2774
+ models: modelOptions(sources.providers),
2775
+ ...fallback ? { defaultModel: modelId(fallback) } : {}
2776
+ };
2777
+ }
2346
2778
  async createThread(input) {
2347
2779
  const connection = this.#requireConnection();
2780
+ const sources = await this.#modelSources(connection);
2781
+ const modelSelection = pickedSelection(sources.providers, input.model) ?? this.#options.modelSelection ?? resolveModelSelection(sources);
2782
+ if (!modelSelection) throw new Error("T3 Code has no usable provider. Set one up in T3 Code → Settings → Providers.");
2348
2783
  const threadId = randomUUID();
2784
+ this.#log(`New thread on ${modelId(modelSelection)}`);
2349
2785
  await connection.protocol.startThread(connection.socket, {
2350
2786
  threadId,
2351
2787
  projectId: connection.project.id,
2352
2788
  title: input.title,
2353
2789
  text: input.text,
2354
2790
  attachments: input.attachments,
2355
- modelSelection: connection.modelSelection,
2791
+ modelSelection,
2356
2792
  runtimeMode: this.#runtimeMode(),
2357
2793
  interactionMode: this.#options.interactionMode ?? "default"
2358
2794
  });
@@ -2412,7 +2848,7 @@ var T3CodeProvider = class {
2412
2848
  state: "ready",
2413
2849
  target: connection.project.title
2414
2850
  });
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}`);
2851
+ this.#log(`Connected to T3 Code at ${this.#baseUrl} · project "${connection.project.title}" · protocol v${connection.protocol.version}`);
2416
2852
  for (const [threadId, watcher] of this.#watchers) this.#subscribe(connection, threadId, watcher);
2417
2853
  } catch (error) {
2418
2854
  unauthorized = error instanceof UnauthorizedError;
@@ -2453,7 +2889,6 @@ var T3CodeProvider = class {
2453
2889
  socket.requestTimeoutMs = this.#timeouts.rpcMs;
2454
2890
  try {
2455
2891
  const project = await this.#resolveProject(socket, protocol, token);
2456
- const modelSelection = this.#options.modelSelection ?? project.defaultModelSelection ?? await this.#defaultModelSelection(socket);
2457
2892
  socket.onClose((reason) => {
2458
2893
  if (this.#connection?.socket !== socket) return;
2459
2894
  this.#connection = void 0;
@@ -2469,8 +2904,7 @@ var T3CodeProvider = class {
2469
2904
  socket,
2470
2905
  protocol,
2471
2906
  environmentId: environment.environmentId,
2472
- project,
2473
- modelSelection
2907
+ project
2474
2908
  };
2475
2909
  } catch (error) {
2476
2910
  socket.close();
@@ -2516,16 +2950,6 @@ var T3CodeProvider = class {
2516
2950
  this.#hadProject = true;
2517
2951
  return project;
2518
2952
  }
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
2953
  #subscribe(connection, threadId, watcher) {
2530
2954
  watcher.cancel?.();
2531
2955
  watcher.tracker = connection.protocol.createTracker();
@@ -2608,7 +3032,7 @@ function errorMessage(error) {
2608
3032
  }
2609
3033
  //#endregion
2610
3034
  //#region src/version.ts
2611
- const VERSION = "0.3.2";
3035
+ const VERSION = "0.4.0";
2612
3036
  //#endregion
2613
3037
  //#region src/daemon/thread-store.ts
2614
3038
  const StoreFile = z.object({
@@ -2636,7 +3060,7 @@ function projectStorePath(projectRoot, dataDir = defaultDataDir()) {
2636
3060
  * Pins for one project, persisted outside the repo so they survive bridge
2637
3061
  * restarts without leaving files in the project. Writes are debounced and atomic.
2638
3062
  */
2639
- var ThreadStore = class {
3063
+ var FileThreadStore = class {
2640
3064
  path;
2641
3065
  #root;
2642
3066
  #threads = /* @__PURE__ */ new Map();
@@ -2651,13 +3075,7 @@ var ThreadStore = class {
2651
3075
  if (raw === void 0) return;
2652
3076
  const parsed = StoreFile.safeParse(JSON.parse(raw));
2653
3077
  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
- }
3078
+ for (const thread of parsed.data.threads) this.#threads.set(thread.id, settleInterrupted(thread));
2661
3079
  }
2662
3080
  list() {
2663
3081
  return [...this.#threads.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -2778,92 +3196,41 @@ async function hasClaudeCode() {
2778
3196
  return (await Promise.all(candidates.map((path) => access(path).then(() => true, () => false)))).includes(true);
2779
3197
  }
2780
3198
  //#endregion
2781
- //#region src/daemon/project-providers.ts
3199
+ //#region src/daemon/project-settings.ts
2782
3200
  const SettingsFile = z.object({
2783
3201
  version: z.literal(1),
2784
3202
  /** The provider new pins go to; unset means the daemon's `--provider`. */
2785
- provider: z.string().optional()
3203
+ provider: z.string().optional(),
3204
+ /** Model picked per provider for new threads; unset means the provider's default. */
3205
+ models: z.record(z.string(), z.string()).optional(),
3206
+ /** Queue new comments and send them together. */
3207
+ batch: z.boolean().optional()
2786
3208
  });
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;
3209
+ /** A project's settings live next to its pins: `<slug>-<hash>.settings.json`. */
3210
+ function projectSettingsPath(projectRoot, dataDir = defaultDataDir()) {
3211
+ return projectStorePath(projectRoot, dataDir).replace(/\.json$/, ".settings.json");
3212
+ }
3213
+ /** A project's overlay settings (provider, models, batching) in a JSON file. */
3214
+ var FileProjectSettings = class {
3215
+ path;
3216
+ constructor(path) {
3217
+ this.path = path;
2814
3218
  }
2815
3219
  async load() {
2816
- if (!this.#options.settingsPath) return;
2817
- const raw = await readFile(this.#options.settingsPath, "utf8").catch(() => void 0);
3220
+ const raw = await readFile(this.path, "utf8").catch(() => void 0);
2818
3221
  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);
3222
+ return parsed?.success ? parsed.data : void 0;
2827
3223
  }
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`;
3224
+ async save(settings) {
3225
+ await mkdir(dirname(this.path), { recursive: true });
3226
+ const temp = `${this.path}.tmp`;
2862
3227
  await writeFile(temp, `${JSON.stringify({
2863
3228
  version: 1,
2864
- provider: this.#chosen
3229
+ provider: settings.provider,
3230
+ models: settings.models,
3231
+ batch: settings.batch
2865
3232
  }, null, 2)}\n`);
2866
- await rename(temp, path);
3233
+ await rename(temp, this.path);
2867
3234
  }
2868
3235
  };
2869
3236
  //#endregion
@@ -2976,9 +3343,9 @@ async function startDaemon(options = {}) {
2976
3343
  t3Url
2977
3344
  }),
2978
3345
  create: (id) => createProvider(key, id),
2979
- settingsPath: projectStorePath(key, dataDir).replace(/\.json$/, ".settings.json")
3346
+ settings: new FileProjectSettings(projectSettingsPath(key, dataDir))
2980
3347
  });
2981
- const store = new ThreadStore(key, dataDir);
3348
+ const store = new FileThreadStore(key, dataDir);
2982
3349
  await Promise.all([store.load(), providers.load()]);
2983
3350
  const bridge = new Bridge({
2984
3351
  providers,
@@ -3202,4 +3569,4 @@ function resolveOverlayPath() {
3202
3569
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
3203
3570
  }
3204
3571
  //#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 };
3572
+ 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 };