tencil 0.12.0 → 0.14.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.
@@ -149,6 +149,8 @@ const Preferences = z.object({
149
149
  ]).optional(),
150
150
  shortcuts: Shortcuts.optional()
151
151
  });
152
+ /** The longest instructions a user can save to go with every pin. */
153
+ const CONTEXT_MAX = 1e4;
152
154
  const ClientMessage = z.discriminatedUnion("type", [
153
155
  z.object({
154
156
  type: z.literal("hello"),
@@ -229,7 +231,11 @@ const ClientMessage = z.discriminatedUnion("type", [
229
231
  type: z.literal("settings.update"),
230
232
  provider: z.string().min(1).optional(),
231
233
  batch: z.boolean().optional(),
232
- ruler: z.boolean().optional()
234
+ ruler: z.boolean().optional(),
235
+ /** Instructions for every pin of this project; empty clears them. */
236
+ context: z.string().max(CONTEXT_MAX).optional(),
237
+ /** Instructions for every pin of every project (where the host keeps them). */
238
+ globalContext: z.string().max(CONTEXT_MAX).optional()
233
239
  }),
234
240
  z.object({
235
241
  type: z.literal("model.select"),
@@ -270,7 +276,14 @@ z.object({
270
276
  /** New comments are queued and sent together. */
271
277
  batch: z.boolean(),
272
278
  /** The toolbar offers the ruler: spacing while picking, distances with Alt. */
273
- ruler: z.boolean()
279
+ ruler: z.boolean(),
280
+ /** Instructions that go with every pin of this project; empty when there are none. */
281
+ context: z.string(),
282
+ /**
283
+ * Instructions that go with every pin of every project. Left out where the
284
+ * host has nowhere to keep them; the overlay then doesn't offer them.
285
+ */
286
+ globalContext: z.string().optional()
274
287
  });
275
288
  /**
276
289
  * How the daemon matched the page to its project: an Ensemble thread's dev
@@ -464,10 +477,12 @@ const CONTEXT_CLOSE = "</tencil-context>";
464
477
  function renderPrompt(input) {
465
478
  const lines = [
466
479
  "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.",
480
+ ...deployedNote([input.pageUrl]),
467
481
  "",
468
482
  ...contextLines(input.pageUrl, input.context)
469
483
  ];
470
484
  if (input.hasScreenshot) lines.push("- A screenshot of the element is attached.");
485
+ lines.push(...instructionLines(input.instructions));
471
486
  return `${input.prompt.trim()}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
472
487
  }
473
488
  /**
@@ -475,24 +490,25 @@ function renderPrompt(input) {
475
490
  * their pins, then one context block with a section per comment. Stripping
476
491
  * the block leaves the numbered comments.
477
492
  */
478
- function renderBatchPrompt(comments) {
479
- 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.`];
493
+ function renderBatchPrompt(comments, instructions) {
494
+ 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.`, ...deployedNote(comments.map((comment) => comment.pageUrl))];
480
495
  for (const comment of comments) {
481
496
  lines.push("", `#${comment.number}`, ...contextLines(comment.pageUrl, comment.context));
482
497
  if (comment.screenshots.length > 0) lines.push(`- Screenshot: attached image ${comment.screenshots.join(", ")}`);
483
498
  }
499
+ lines.push(...instructionLines(instructions));
484
500
  return `${comments.map((comment) => `#${comment.number} ${comment.prompt.trim()}`).join("\n\n")}\n\n${CONTEXT_OPEN}\n${lines.join("\n")}\n${CONTEXT_CLOSE}`;
485
501
  }
486
502
  function contextLines(pageUrl, context) {
487
- const lines = [`- Page: ${page(pageUrl)}`, `- Element: \`${page(truncate(oneLine(context.html), 2e3))}\``];
503
+ const lines = [`- Page: ${page$1(pageUrl)}${isDeployed(pageUrl) ? " (deployed site, not a local dev server)" : ""}`, `- Element: \`${page$1(truncate(oneLine(context.html), 2e3))}\``];
488
504
  const [component, ...owners] = context.components;
489
505
  if (component) {
490
506
  const chain = [component, ...owners.slice(0, 4)].map(formatFrame).join(" ← ");
491
- lines.push(`- Component: ${page(chain)}`);
507
+ lines.push(`- Component: ${page$1(chain)}`);
492
508
  }
493
- lines.push(`- Selector: \`${page(truncate(context.selector, 500))}\``);
494
- if (context.text) lines.push(`- Visible text: "${page(truncate(oneLine(context.text), 200))}"`);
495
- if (context.selection) lines.push(`- Selected text: "${page(truncate(oneLine(context.selection), 300))}"`);
509
+ lines.push(`- Selector: \`${page$1(truncate(context.selector, 500))}\``);
510
+ if (context.text) lines.push(`- Visible text: "${page$1(truncate(oneLine(context.text), 200))}"`);
511
+ if (context.selection) lines.push(`- Selected text: "${page$1(truncate(oneLine(context.selection), 300))}"`);
496
512
  const { rect, viewport } = context;
497
513
  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`);
498
514
  const box = context.box && boxLine(context.box);
@@ -500,6 +516,41 @@ function contextLines(pageUrl, context) {
500
516
  if (context.spacing) lines.push(spacingLine(context.spacing));
501
517
  return lines;
502
518
  }
519
+ /**
520
+ * The user's standing instructions, global first, then the project's. They're
521
+ * the user's own words but go inside the block, so the agent reads them as
522
+ * context for the change and the overlay doesn't show them on every pin.
523
+ */
524
+ function instructionLines(instructions = {}) {
525
+ const lines = [];
526
+ const sections = [["The user asks this for every project:", instructions.global], ["The user asks this for this project:", instructions.project]];
527
+ for (const [heading, text] of sections) {
528
+ const trimmed = text?.trim();
529
+ if (trimmed) lines.push("", heading, page$1(trimmed));
530
+ }
531
+ return lines;
532
+ }
533
+ /**
534
+ * When a pin was made on a deployed site (through the extension) rather than the
535
+ * local dev server, the agent should know its edit won't show there until it ships,
536
+ * and that a production build may have no component names or source paths.
537
+ */
538
+ function deployedNote(pageUrls) {
539
+ const origins = [...new Set(pageUrls.filter(isDeployed).map((url) => new URL(url).origin))];
540
+ if (origins.length === 0) return [];
541
+ return [`The page is on ${page$1(origins.join(", "))}, a deployed site, not this workspace's dev server. Change the source here; the change won't show on that site until it's deployed, so say so when you report back. A production build may not name components or their source files: find the code by its visible text, markup and selector.`];
542
+ }
543
+ /** Anything but a loopback, private-network or local-only host (`.local`, `.test`). */
544
+ function isDeployed(pageUrl) {
545
+ let hostname;
546
+ try {
547
+ hostname = new URL(pageUrl).hostname.toLowerCase();
548
+ } catch {
549
+ return false;
550
+ }
551
+ if (!hostname) return false;
552
+ return !(hostname === "localhost" || /\.(localhost|local|test|internal)$/.test(hostname) || hostname === "[::1]" || hostname === "0.0.0.0" || /^127(\.\d{1,3}){3}$/.test(hostname) || /^10(\.\d{1,3}){3}$/.test(hostname) || /^192\.168(\.\d{1,3}){2}$/.test(hostname) || /^172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}$/.test(hostname));
553
+ }
503
554
  /** Computed spacing in CSS shorthand, px: `padding 12 16, margin 0 0 24, gap 8`. */
504
555
  function boxLine(box) {
505
556
  const parts = [];
@@ -533,7 +584,7 @@ function spacingLine(spacing) {
533
584
  "bottom",
534
585
  "left"
535
586
  ].filter((side) => spacing[side] !== void 0).map((side) => `${spacing[side]}px ${SIDE_WORDS[side]}`);
536
- return `- Measured spacing to ${`${spacing.parent ? "its parent " : ""}\`${page(truncate(spacing.to, 200))}\``}${spacing.selector ? ` (\`${page(truncate(spacing.selector, 500))}\`)` : ""}: ${sides.length > 0 ? sides.join(", ") : "none"}`;
587
+ return `- Measured spacing to ${`${spacing.parent ? "its parent " : ""}\`${page$1(truncate(spacing.to, 200))}\``}${spacing.selector ? ` (\`${page$1(truncate(spacing.selector, 500))}\`)` : ""}: ${sides.length > 0 ? sides.join(", ") : "none"}`;
537
588
  }
538
589
  function stripContext(text) {
539
590
  const index = text.indexOf(CONTEXT_OPEN);
@@ -557,7 +608,7 @@ function formatFrame(frame) {
557
608
  * to close that block early and pass the rest off as the user's words, so the
558
609
  * block's tags are defused wherever they appear in it.
559
610
  */
560
- function page(text) {
611
+ function page$1(text) {
561
612
  return text.replace(/<(\/?\s*tencil-context)/gi, "‹$1");
562
613
  }
563
614
  function oneLine(text) {
@@ -586,6 +637,7 @@ var Bridge = class {
586
637
  #offInfo = () => {};
587
638
  #offDefault;
588
639
  #offSettings;
640
+ #offGlobalContext;
589
641
  constructor(options) {
590
642
  this.#options = options;
591
643
  this.#followDefault();
@@ -604,6 +656,10 @@ var Bridge = class {
604
656
  type: "settings",
605
657
  settings: this.#settings()
606
658
  }));
659
+ this.#offGlobalContext = options.globalContext?.onChange(() => this.#broadcast({
660
+ type: "settings",
661
+ settings: this.#settings()
662
+ })) ?? (() => {});
607
663
  for (const thread of options.store.list()) if (thread.provider.threadId && options.providers.has(thread.provider.id) && !this.#archived(thread.provider)) this.#watch(thread.provider.id, thread.provider.threadId);
608
664
  }
609
665
  connect(client) {
@@ -674,6 +730,12 @@ var Bridge = class {
674
730
  if (message.provider) await providers.setDefault(message.provider);
675
731
  if (message.batch !== void 0) await providers.setBatch(message.batch);
676
732
  if (message.ruler !== void 0) await providers.setRuler(message.ruler);
733
+ if (message.context !== void 0) await providers.setContext(message.context);
734
+ if (message.globalContext !== void 0) {
735
+ const { globalContext } = this.#options;
736
+ if (!globalContext) throw new Error("Instructions for every project aren't saved here");
737
+ await globalContext.set(message.globalContext);
738
+ }
677
739
  return;
678
740
  }
679
741
  case "provider.models": {
@@ -736,6 +798,7 @@ var Bridge = class {
736
798
  this.#offInfo();
737
799
  this.#offDefault();
738
800
  this.#offSettings();
801
+ this.#offGlobalContext();
739
802
  for (const unwatch of this.#watches.values()) unwatch();
740
803
  for (const timer of this.#pendingBroadcast.values()) clearTimeout(timer);
741
804
  await this.#options.store.flush();
@@ -767,7 +830,8 @@ var Bridge = class {
767
830
  prompt: message.prompt,
768
831
  pageUrl: message.pageUrl,
769
832
  context: message.context,
770
- hasScreenshot: message.attachments.length > 0
833
+ hasScreenshot: message.attachments.length > 0,
834
+ instructions: this.#instructions()
771
835
  }),
772
836
  attachments: message.attachments,
773
837
  model: this.#options.providers.modelFor(provider.id)
@@ -841,8 +905,9 @@ var Bridge = class {
841
905
  });
842
906
  const text = drafts.length === 1 ? renderPrompt({
843
907
  ...comments[0],
844
- hasScreenshot: attachments.length > 0
845
- }) : renderBatchPrompt(comments);
908
+ hasScreenshot: attachments.length > 0,
909
+ instructions: this.#instructions()
910
+ }) : renderBatchPrompt(comments, this.#instructions());
846
911
  const now = (/* @__PURE__ */ new Date()).toISOString();
847
912
  const echo = localMessage(stripContext(text), now);
848
913
  for (const { thread } of drafts) this.#update(thread.id, (current) => ({
@@ -919,7 +984,8 @@ var Bridge = class {
919
984
  prompt: message.prompt,
920
985
  pageUrl: message.pageUrl,
921
986
  context: message.context,
922
- hasScreenshot: message.attachments.length > 0
987
+ hasScreenshot: message.attachments.length > 0,
988
+ instructions: this.#instructions()
923
989
  }),
924
990
  attachments: message.attachments
925
991
  });
@@ -1086,7 +1152,16 @@ var Bridge = class {
1086
1152
  providers: providers.choices,
1087
1153
  ...model ? { model } : {},
1088
1154
  batch: providers.batch,
1089
- ruler: providers.ruler
1155
+ ruler: providers.ruler,
1156
+ context: providers.context,
1157
+ ...this.#options.globalContext && { globalContext: this.#options.globalContext.get() }
1158
+ };
1159
+ }
1160
+ /** What the user's settings say goes with every new pin. */
1161
+ #instructions() {
1162
+ return {
1163
+ global: this.#options.globalContext?.get(),
1164
+ project: this.#options.providers.context
1090
1165
  };
1091
1166
  }
1092
1167
  #require(threadId) {
@@ -1190,6 +1265,7 @@ var ProjectProviders = class ProjectProviders {
1190
1265
  #batch = true;
1191
1266
  /** On unless the project turns it off. */
1192
1267
  #ruler = true;
1268
+ #context = "";
1193
1269
  constructor(options) {
1194
1270
  this.#options = options;
1195
1271
  this.choices = options.choices;
@@ -1221,6 +1297,7 @@ var ProjectProviders = class ProjectProviders {
1221
1297
  this.#models = saved.models ?? {};
1222
1298
  this.#batch = saved.batch ?? true;
1223
1299
  this.#ruler = saved.ruler ?? true;
1300
+ this.#context = saved.context ?? "";
1224
1301
  }
1225
1302
  }
1226
1303
  get defaultId() {
@@ -1283,7 +1360,17 @@ var ProjectProviders = class ProjectProviders {
1283
1360
  await this.#save();
1284
1361
  for (const listener of this.#settingsListeners) listener();
1285
1362
  }
1286
- /** Fires when a picked model, batching or the ruler changes. */
1363
+ /** The project's instructions for every pin, empty when there are none. */
1364
+ get context() {
1365
+ return this.#context;
1366
+ }
1367
+ async setContext(context) {
1368
+ if (context === this.#context) return;
1369
+ this.#context = context;
1370
+ await this.#save();
1371
+ for (const listener of this.#settingsListeners) listener();
1372
+ }
1373
+ /** Fires when a picked model, batching, the ruler or the context changes. */
1287
1374
  onSettingsChange(listener) {
1288
1375
  this.#settingsListeners.add(listener);
1289
1376
  return () => this.#settingsListeners.delete(listener);
@@ -1301,7 +1388,8 @@ var ProjectProviders = class ProjectProviders {
1301
1388
  provider: this.#chosen,
1302
1389
  models: this.#models,
1303
1390
  batch: this.#batch,
1304
- ruler: this.#ruler
1391
+ ruler: this.#ruler,
1392
+ ...this.#context ? { context: this.#context } : {}
1305
1393
  });
1306
1394
  }
1307
1395
  };
@@ -3550,6 +3638,8 @@ var CodexProvider = class {
3550
3638
  /** The process behind `#server`, known from the moment it starts. */
3551
3639
  #current;
3552
3640
  #idleTimer;
3641
+ /** Calls in progress: the idle close waits for them, as it does for a turn. */
3642
+ #inUse = 0;
3553
3643
  #recheckTimer;
3554
3644
  #sessions = /* @__PURE__ */ new Map();
3555
3645
  #disposed = false;
@@ -3560,17 +3650,19 @@ var CodexProvider = class {
3560
3650
  async start() {
3561
3651
  clearTimeout(this.#recheckTimer);
3562
3652
  try {
3563
- const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3564
- const { account, requiresOpenaiAuth } = await server.request("account/read", {});
3565
- if (!account && requiresOpenaiAuth) {
3566
- this.#signedOut(NOT_SIGNED_IN);
3567
- return;
3568
- }
3569
- this.#setInfo({
3570
- state: "ready",
3571
- target: basename(workspace)
3653
+ await this.#using(async () => {
3654
+ const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3655
+ const { account, requiresOpenaiAuth } = await server.request("account/read", {});
3656
+ if (!account && requiresOpenaiAuth) {
3657
+ this.#signedOut(NOT_SIGNED_IN);
3658
+ return;
3659
+ }
3660
+ this.#setInfo({
3661
+ state: "ready",
3662
+ target: basename(workspace)
3663
+ });
3664
+ this.#log(`Codex ready in ${workspace}`);
3572
3665
  });
3573
- this.#log(`Codex ready in ${workspace}`);
3574
3666
  } catch (error) {
3575
3667
  this.#setInfo({
3576
3668
  state: "unavailable",
@@ -3586,7 +3678,10 @@ var CodexProvider = class {
3586
3678
  this.#infoListeners.add(listener);
3587
3679
  return () => this.#infoListeners.delete(listener);
3588
3680
  }
3589
- async listThreads() {
3681
+ listThreads() {
3682
+ return this.#using(() => this.#listThreads());
3683
+ }
3684
+ async #listThreads() {
3590
3685
  const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3591
3686
  const { data } = await server.request("thread/list", {
3592
3687
  cwd: workspace,
@@ -3606,7 +3701,10 @@ var CodexProvider = class {
3606
3701
  threads
3607
3702
  };
3608
3703
  }
3609
- async listModels() {
3704
+ listModels() {
3705
+ return this.#using(() => this.#listModels());
3706
+ }
3707
+ async #listModels() {
3610
3708
  const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3611
3709
  const available = await pages((cursor) => server.request("model/list", {
3612
3710
  cursor,
@@ -3625,7 +3723,10 @@ var CodexProvider = class {
3625
3723
  };
3626
3724
  }
3627
3725
  threadUrl() {}
3628
- async createThread(input) {
3726
+ createThread(input) {
3727
+ return this.#using(() => this.#createThread(input));
3728
+ }
3729
+ async #createThread(input) {
3629
3730
  const [server, workspace, model] = await Promise.all([
3630
3731
  this.#connect(),
3631
3732
  this.#workspaceRoot(),
@@ -3645,7 +3746,10 @@ var CodexProvider = class {
3645
3746
  await this.#startTurn(session, server, input.text, input.attachments);
3646
3747
  return { providerThreadId: thread.id };
3647
3748
  }
3648
- async sendMessage(input) {
3749
+ sendMessage(input) {
3750
+ return this.#using(() => this.#sendMessage(input));
3751
+ }
3752
+ async #sendMessage(input) {
3649
3753
  const session = this.#session(input.providerThreadId);
3650
3754
  const [server, workspace] = await Promise.all([this.#connect(), this.#workspaceRoot()]);
3651
3755
  if (session.server !== server) {
@@ -3707,7 +3811,7 @@ var CodexProvider = class {
3707
3811
  }
3708
3812
  /** Load the conversation Codex saved, once. */
3709
3813
  #hydrate(session) {
3710
- session.hydrated ??= (async () => {
3814
+ session.hydrated ??= this.#using(async () => {
3711
3815
  const server = await this.#connect();
3712
3816
  try {
3713
3817
  for (const message of messagesFromHistory(await readHistory(server, session.id))) if (!session.messages.has(message.id)) session.messages.set(message.id, message);
@@ -3715,7 +3819,7 @@ var CodexProvider = class {
3715
3819
  if (!isMissingThread(error)) throw error;
3716
3820
  session.missing = true;
3717
3821
  }
3718
- })().catch((error) => {
3822
+ }).catch((error) => {
3719
3823
  session.hydrated = void 0;
3720
3824
  throw error;
3721
3825
  });
@@ -3860,11 +3964,21 @@ var CodexProvider = class {
3860
3964
  #keepOpen() {
3861
3965
  clearTimeout(this.#idleTimer);
3862
3966
  this.#idleTimer = setTimeout(() => {
3863
- if ([...this.#sessions.values()].some((session) => session.tracker.status().status === "working")) this.#keepOpen();
3967
+ if ([...this.#sessions.values()].some((session) => session.tracker.status().status === "working") || this.#inUse > 0) this.#keepOpen();
3864
3968
  else this.#closeServer();
3865
3969
  }, this.#options.idleCloseMs ?? DEFAULT_IDLE_CLOSE_MS);
3866
3970
  this.#idleTimer.unref?.();
3867
3971
  }
3972
+ /** Keep the process for the whole of `work`, then a while longer. */
3973
+ async #using(work) {
3974
+ this.#inUse++;
3975
+ try {
3976
+ return await work();
3977
+ } finally {
3978
+ this.#inUse--;
3979
+ this.#keepOpen();
3980
+ }
3981
+ }
3868
3982
  #closeServer() {
3869
3983
  clearTimeout(this.#idleTimer);
3870
3984
  const server = this.#server;
@@ -5311,7 +5425,7 @@ function errorMessage(error) {
5311
5425
  }
5312
5426
  //#endregion
5313
5427
  //#region src/version.ts
5314
- const VERSION = "0.12.0";
5428
+ const VERSION = "0.14.0";
5315
5429
  //#endregion
5316
5430
  //#region src/daemon/thread-store.ts
5317
5431
  const StoreFile = z.object({
@@ -5433,29 +5547,43 @@ const providerLabel = (id) => PROVIDER_OPTIONS.find((option) => option.id === id
5433
5547
  const SettingsFile$1 = z.object({
5434
5548
  version: z.literal(1),
5435
5549
  /** The agent of projects that haven't picked one in the overlay. */
5436
- provider: z.enum(PROVIDERS).optional()
5550
+ provider: z.enum(PROVIDERS).optional(),
5551
+ /** Instructions that go with every pin of every project. */
5552
+ context: z.string().optional()
5437
5553
  });
5438
5554
  const settingsPath = (dataDir) => join(dataDir, "settings.json");
5439
- /** The agent chosen for this machine (by setup or `--provider`), if any. */
5440
- async function savedProvider(dataDir = defaultDataDir()) {
5555
+ /** This machine's settings; empty when there are none or the file is broken. */
5556
+ async function readSettings(dataDir = defaultDataDir()) {
5441
5557
  const raw = await readFile(settingsPath(dataDir), "utf8").catch(() => void 0);
5442
- if (raw === void 0) return void 0;
5558
+ if (raw === void 0) return {};
5443
5559
  try {
5444
5560
  const parsed = SettingsFile$1.safeParse(JSON.parse(raw));
5445
- return parsed.success ? parsed.data.provider : void 0;
5561
+ if (!parsed.success) return {};
5562
+ const { version: _, ...settings } = parsed.data;
5563
+ return settings;
5446
5564
  } catch {
5447
- return;
5565
+ return {};
5448
5566
  }
5449
5567
  }
5450
- async function saveProvider(provider, dataDir = defaultDataDir()) {
5568
+ /** Merges `changes` into the saved settings; an undefined value removes that setting. */
5569
+ async function writeSettings(changes, dataDir = defaultDataDir()) {
5451
5570
  const path = settingsPath(dataDir);
5452
- await mkdir(dirname(path), { recursive: true });
5453
- await writeFile(`${path}.tmp`, `${JSON.stringify({
5571
+ const next = {
5454
5572
  version: 1,
5455
- provider
5456
- }, null, 2)}\n`);
5573
+ ...await readSettings(dataDir),
5574
+ ...changes
5575
+ };
5576
+ await mkdir(dirname(path), { recursive: true });
5577
+ await writeFile(`${path}.tmp`, `${JSON.stringify(next, null, 2)}\n`);
5457
5578
  await rename(`${path}.tmp`, path);
5458
5579
  }
5580
+ /** The agent chosen for this machine (by setup or `--provider`), if any. */
5581
+ async function savedProvider(dataDir = defaultDataDir()) {
5582
+ return (await readSettings(dataDir)).provider;
5583
+ }
5584
+ async function saveProvider(provider, dataDir = defaultDataDir()) {
5585
+ await writeSettings({ provider }, dataDir);
5586
+ }
5459
5587
  /**
5460
5588
  * Which agents this machine has: a paired or running T3 Code, an installed
5461
5589
  * Claude Code, Codex's CLI or desktop app, a running Ensemble app.
@@ -5507,6 +5635,218 @@ async function hasClaudeCode() {
5507
5635
  return (await Promise.all(candidates.map((path) => access(path).then(() => true, () => false)))).includes(true);
5508
5636
  }
5509
5637
  //#endregion
5638
+ //#region src/daemon/allowed-origins.ts
5639
+ /**
5640
+ * Sites the developer let talk to the daemon from the approval page, on top of
5641
+ * loopback ones and `--allow-origin`. Kept in memory: the WebSocket upgrade
5642
+ * checks it synchronously.
5643
+ */
5644
+ var AllowedOrigins = class {
5645
+ path;
5646
+ #fixed;
5647
+ #approved;
5648
+ constructor(path, fixed = []) {
5649
+ this.path = path;
5650
+ this.#fixed = fixed;
5651
+ this.#approved = read(path);
5652
+ }
5653
+ all() {
5654
+ return [...this.#fixed, ...this.#approved];
5655
+ }
5656
+ add(origin) {
5657
+ if (this.all().includes(origin)) return;
5658
+ this.#approved = [...this.#approved, origin];
5659
+ mkdirSync(dirname(this.path), { recursive: true });
5660
+ writeFileSync(this.path, `${JSON.stringify(this.#approved, null, 2)}\n`);
5661
+ }
5662
+ };
5663
+ /** The origin a page may ask to be allowed: http(s) and nothing but scheme, host and port. */
5664
+ function approvableOrigin(value) {
5665
+ if (!value) return void 0;
5666
+ try {
5667
+ const url = new URL(value);
5668
+ if (url.protocol !== "http:" && url.protocol !== "https:") return void 0;
5669
+ return url.origin === value ? value : void 0;
5670
+ } catch {
5671
+ return;
5672
+ }
5673
+ }
5674
+ function read(path) {
5675
+ try {
5676
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
5677
+ return Array.isArray(parsed) ? parsed.filter((o) => approvableOrigin(o) === o) : [];
5678
+ } catch {
5679
+ return [];
5680
+ }
5681
+ }
5682
+ //#endregion
5683
+ //#region src/daemon/approval-page.ts
5684
+ /**
5685
+ * The page where the developer lets a site talk to the daemon. It's served by the
5686
+ * daemon itself, so the site asking can't frame it, script it or click it.
5687
+ */
5688
+ /** No framing (clickjacking), no outside resources, forms only back to the daemon. */
5689
+ const APPROVAL_HEADERS = {
5690
+ "content-type": "text/html; charset=utf-8",
5691
+ "cache-control": "no-store",
5692
+ "x-frame-options": "DENY",
5693
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"
5694
+ };
5695
+ function confirmPage(origin) {
5696
+ return page(`Let ${escapeHtml(origin)} use Tencil?`, `<p>The Tencil overlay on <strong>${escapeHtml(origin)}</strong> wants to connect to the
5697
+ daemon on this machine.</p>
5698
+ <p class="warn"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4M12 17h.01"/></svg><span>Once allowed, any script on that site can send prompts to your coding
5699
+ agent while Tencil runs, so only allow sites you trust.</span></p>
5700
+ <form method="post" action="/allow">
5701
+ <input type="hidden" name="origin" value="${escapeHtml(origin)}">
5702
+ <button type="button" class="secondary" onclick="window.close()">Cancel</button>
5703
+ <button type="submit">Allow</button>
5704
+ </form>`);
5705
+ }
5706
+ function allowedPage(origin) {
5707
+ return page(`${escapeHtml(origin)} can use Tencil`, `<p class="done"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>Go back to the site; the overlay connects on its own.</p>
5708
+ <p class="muted">To take it back, remove it from <code>allowed-origins.json</code> in
5709
+ Tencil's data folder and restart the daemon.</p>
5710
+ <script>setTimeout(() => window.close(), 600)<\/script>`);
5711
+ }
5712
+ function errorPage(message) {
5713
+ return page("Couldn't allow this site", `<p>${escapeHtml(message)}</p>`);
5714
+ }
5715
+ /** Tencil's mark, as in the overlay: the pin with a cursor cut out of it. */
5716
+ const LOGO = `<svg class="logo" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true"><path fill="#3b62ff" fill-rule="evenodd" transform="translate(3 3) scale(0.140625)" d="M80 0C106.51 0 128 21.4903 128 48V80C128 106.51 106.51 128 80 128H4C1.79086 128 0 126.209 0 124V48C0 21.4903 21.4903 0 48 0H80ZM102.06 31.19A4 4 0 0 0 96.81 25.94L17.67 59.86A4 4 0 0 0 17.98 67.33L48.1 77.37A4 4 0 0 1 50.63 79.9L60.67 110.02A4 4 0 0 0 68.14 110.33Z"/></svg>`;
5717
+ /** Styled like the overlay's panels: same neutrals, accent, radius and shadow. */
5718
+ function page(title, body) {
5719
+ return `<!doctype html>
5720
+ <html lang="en">
5721
+ <head>
5722
+ <meta charset="utf-8">
5723
+ <meta name="viewport" content="width=device-width, initial-scale=1">
5724
+ <title>${title} · Tencil</title>
5725
+ <style>
5726
+ :root {
5727
+ --n-50: hsl(120 4% 97%); --n-100: hsl(120 2% 92%); --n-200: hsl(90 2% 82%);
5728
+ --n-500: hsl(96 2% 50%); --n-700: hsl(100 2% 28%); --n-950: hsl(60 4% 5%);
5729
+ --surface: #fff;
5730
+ --accent: hsl(214 67% 51%); --accent-hover: hsl(214 62% 45%);
5731
+ --warn: #b7791f; --warn-soft: hsl(38 80% 50% / 0.1);
5732
+ --done: #1a896b;
5733
+ --ease-out: cubic-bezier(0.23, 1, 0.32, 1);
5734
+ --shadow: 0 0 0 1px rgba(0, 0, 0, 0.06), 0 4px 8px -2px rgba(0, 0, 0, 0.06),
5735
+ 0 16px 40px -8px rgba(0, 0, 0, 0.16);
5736
+ color-scheme: light;
5737
+ }
5738
+ @media (prefers-color-scheme: dark) {
5739
+ :root {
5740
+ --n-50: hsl(60 4% 7%); --n-100: hsl(90 2% 13%); --n-200: hsl(100 2% 21%);
5741
+ --n-500: hsl(96 2% 52%); --n-700: hsl(100 2% 76%); --n-950: hsl(120 4% 96%);
5742
+ --surface: hsl(90 2% 10%);
5743
+ --accent-hover: hsl(214 67% 58%);
5744
+ --warn: #f5b84a; --warn-soft: hsl(38 90% 60% / 0.1);
5745
+ --done: #3dd6a4;
5746
+ --shadow: 0 0 0 1px rgba(255, 255, 255, 0.06), 0 16px 40px -8px rgba(0, 0, 0, 0.6);
5747
+ color-scheme: dark;
5748
+ }
5749
+ }
5750
+ * { box-sizing: border-box; }
5751
+ body {
5752
+ margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
5753
+ background: var(--n-50); color: var(--n-950);
5754
+ font: 13px/1.5 Geist, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
5755
+ letter-spacing: 0.02rem; -webkit-font-smoothing: antialiased;
5756
+ }
5757
+ main {
5758
+ width: min(420px, 100%); padding: 20px; border-radius: 14px;
5759
+ background: var(--surface); box-shadow: var(--shadow);
5760
+ animation: enter 300ms var(--ease-out);
5761
+ }
5762
+ @keyframes enter { from { opacity: 0; transform: translateY(6px) scale(0.98); } }
5763
+ @media (prefers-reduced-motion: reduce) { main { animation: none; } }
5764
+ header {
5765
+ display: flex; align-items: center; gap: 7px;
5766
+ padding-bottom: 12px; margin-bottom: 16px; border-bottom: 1px solid var(--n-100);
5767
+ }
5768
+ header strong { font-size: 13px; font-weight: 600; }
5769
+ header span { margin-left: auto; color: var(--n-500); font-size: 12px; }
5770
+ .logo { flex: none; }
5771
+ h1 { margin: 0 0 8px; font-size: 15px; font-weight: 600; line-height: 1.4; overflow-wrap: anywhere; }
5772
+ p { margin: 0 0 12px; color: var(--n-700); overflow-wrap: anywhere; }
5773
+ strong { color: var(--n-950); font-weight: 600; }
5774
+ .warn {
5775
+ display: flex; gap: 8px; padding: 10px 12px; border-radius: 10px;
5776
+ background: var(--warn-soft); color: var(--warn);
5777
+ }
5778
+ .warn svg { flex: none; margin-top: 2px; }
5779
+ .done { display: flex; align-items: center; gap: 8px; color: var(--n-950); }
5780
+ .done svg { flex: none; color: var(--done); }
5781
+ .muted { color: var(--n-500); font-size: 12px; margin-bottom: 0; }
5782
+ form { display: flex; justify-content: flex-end; gap: 8px; margin-top: 18px; }
5783
+ button {
5784
+ font: inherit; letter-spacing: inherit; font-weight: 500; height: 32px; padding: 0 14px;
5785
+ border-radius: 999px; border: 0; cursor: pointer; background: var(--accent); color: white;
5786
+ transition: background-color 150ms var(--ease-out), transform 150ms var(--ease-out);
5787
+ }
5788
+ button:hover { background: var(--accent-hover); }
5789
+ button:active { transform: scale(0.97); }
5790
+ button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
5791
+ button.secondary { background: var(--n-100); color: var(--n-950); }
5792
+ button.secondary:hover { background: var(--n-200); }
5793
+ code {
5794
+ font: 11.5px ui-monospace, SFMono-Regular, Menlo, monospace;
5795
+ padding: 1px 5px; border-radius: 5px; background: var(--n-100); color: var(--n-950);
5796
+ }
5797
+ </style>
5798
+ </head>
5799
+ <body><main>
5800
+ <header>${LOGO}<strong>Tencil</strong><span>This machine</span></header>
5801
+ <h1>${title}</h1>${body}
5802
+ </main></body>
5803
+ </html>
5804
+ `;
5805
+ }
5806
+ function escapeHtml(text) {
5807
+ return text.replace(/[&<>"']/g, (char) => ({
5808
+ "&": "&amp;",
5809
+ "<": "&lt;",
5810
+ ">": "&gt;",
5811
+ "\"": "&quot;",
5812
+ "'": "&#39;"
5813
+ })[char] ?? char);
5814
+ }
5815
+ //#endregion
5816
+ //#region src/daemon/global-context.ts
5817
+ /**
5818
+ * The instructions that go with every pin of every project on this machine,
5819
+ * kept as `context` in `settings.json` next to the machine's agent. One per
5820
+ * daemon, shared by every project's bridge.
5821
+ */
5822
+ var FileGlobalContext = class {
5823
+ dataDir;
5824
+ #context = "";
5825
+ #listeners = /* @__PURE__ */ new Set();
5826
+ /** Saves run one after another, so a quick second change can't land first. */
5827
+ #writing = Promise.resolve();
5828
+ constructor(dataDir = defaultDataDir()) {
5829
+ this.dataDir = dataDir;
5830
+ }
5831
+ async load() {
5832
+ this.#context = (await readSettings(this.dataDir)).context ?? "";
5833
+ }
5834
+ get() {
5835
+ return this.#context;
5836
+ }
5837
+ async set(context) {
5838
+ if (context === this.#context) return;
5839
+ this.#context = context;
5840
+ for (const listener of this.#listeners) listener();
5841
+ this.#writing = this.#writing.then(() => writeSettings({ context: context || void 0 }, this.dataDir)).catch(() => {});
5842
+ await this.#writing;
5843
+ }
5844
+ onChange(listener) {
5845
+ this.#listeners.add(listener);
5846
+ return () => this.#listeners.delete(listener);
5847
+ }
5848
+ };
5849
+ //#endregion
5510
5850
  //#region src/daemon/preferences.ts
5511
5851
  const PreferencesFile = Preferences.extend({ version: z.literal(1) });
5512
5852
  function preferencesPath(dataDir = defaultDataDir()) {
@@ -5567,13 +5907,15 @@ const SettingsFile = z.object({
5567
5907
  /** Queue new comments and send them together. */
5568
5908
  batch: z.boolean().optional(),
5569
5909
  /** Offer the ruler in the overlay's toolbar. */
5570
- ruler: z.boolean().optional()
5910
+ ruler: z.boolean().optional(),
5911
+ /** Instructions that go with every pin of this project. */
5912
+ context: z.string().optional()
5571
5913
  });
5572
5914
  /** A project's settings live next to its pins: `<slug>-<hash>.settings.json`. */
5573
5915
  function projectSettingsPath(projectRoot, dataDir = defaultDataDir()) {
5574
5916
  return projectStorePath(projectRoot, dataDir).replace(/\.json$/, ".settings.json");
5575
5917
  }
5576
- /** A project's overlay settings (provider, models, batching, ruler) in a JSON file. */
5918
+ /** A project's overlay settings (provider, models, batching, ruler, context) in a JSON file. */
5577
5919
  var FileProjectSettings = class {
5578
5920
  path;
5579
5921
  constructor(path) {
@@ -5592,7 +5934,8 @@ var FileProjectSettings = class {
5592
5934
  provider: settings.provider,
5593
5935
  models: settings.models,
5594
5936
  batch: settings.batch,
5595
- ruler: settings.ruler
5937
+ ruler: settings.ruler,
5938
+ context: settings.context
5596
5939
  }, null, 2)}\n`);
5597
5940
  await rename(temp, this.path);
5598
5941
  }
@@ -6463,9 +6806,9 @@ async function startDaemon(options = {}) {
6463
6806
  const port = options.port ?? 4747;
6464
6807
  const host = options.host ?? "127.0.0.1";
6465
6808
  const addresses = [host, ...(options.listen ?? []).filter((address) => address !== host)];
6466
- const allowedOrigins = options.allowedOrigins ?? [];
6467
- const knownHosts = knownHostsFor(addresses, allowedOrigins);
6809
+ const knownHosts = knownHostsFor(addresses, options.allowedOrigins ?? []);
6468
6810
  const dataDir = options.dataDir ?? defaultDataDir();
6811
+ const allowedOrigins = new AllowedOrigins(join(dataDir, "allowed-origins.json"), options.allowedOrigins);
6469
6812
  const log = options.log ?? (() => {});
6470
6813
  const ensembleOptions = {
6471
6814
  baseUrl: options.ensemble?.url,
@@ -6488,6 +6831,8 @@ async function startDaemon(options = {}) {
6488
6831
  const overlayPath = resolveOverlayPath();
6489
6832
  let updater;
6490
6833
  const preferences = new FilePreferences(preferencesPath(dataDir));
6834
+ const globalContext = new FileGlobalContext(dataDir);
6835
+ const globalContextLoaded = globalContext.load();
6491
6836
  const claudeCodeDir = join(dataDir, "claude-code");
6492
6837
  const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
6493
6838
  const createProvider = options.createProvider ?? ((root, id) => {
@@ -6534,7 +6879,11 @@ async function startDaemon(options = {}) {
6534
6879
  settings: new FileProjectSettings(projectSettingsPath(key, dataDir))
6535
6880
  });
6536
6881
  const store = new FileThreadStore(key, dataDir);
6537
- await Promise.all([store.load(), providers.load()]);
6882
+ await Promise.all([
6883
+ store.load(),
6884
+ providers.load(),
6885
+ globalContextLoaded
6886
+ ]);
6538
6887
  const bridge = new Bridge({
6539
6888
  providers,
6540
6889
  store,
@@ -6544,6 +6893,7 @@ async function startDaemon(options = {}) {
6544
6893
  },
6545
6894
  version: VERSION,
6546
6895
  update: () => updater?.status() ?? { state: "idle" },
6896
+ globalContext,
6547
6897
  log: (message) => log(`[${basename(key)}] ${message}`)
6548
6898
  });
6549
6899
  log(`Serving ${key} with ${providers.default().label}`);
@@ -6616,6 +6966,7 @@ async function startDaemon(options = {}) {
6616
6966
  }
6617
6967
  return;
6618
6968
  }
6969
+ if (url.pathname === "/allow") return handleAllow(request, response, url);
6619
6970
  if (url.pathname === "/health") {
6620
6971
  await refreshStatuses();
6621
6972
  response.writeHead(200, { "content-type": "application/json" });
@@ -6631,15 +6982,55 @@ async function startDaemon(options = {}) {
6631
6982
  response.writeHead(404, { "content-type": "text/plain" });
6632
6983
  response.end("Not found");
6633
6984
  };
6985
+ /**
6986
+ * Letting a site in (`/allow?origin=…`). The overlay opens the page; only a form
6987
+ * posted from the daemon's own page counts, so a site can't approve itself.
6988
+ */
6989
+ const handleAllow = async (request, response, url) => {
6990
+ const reply = (status, html) => {
6991
+ response.writeHead(status, APPROVAL_HEADERS);
6992
+ response.end(html);
6993
+ };
6994
+ if (request.method === "GET") {
6995
+ const origin = approvableOrigin(url.searchParams.get("origin"));
6996
+ if (!origin) return reply(400, errorPage("That is not a site Tencil can allow."));
6997
+ if (allowedOrigins.all().includes(origin)) return reply(200, allowedPage(origin));
6998
+ return reply(200, confirmPage(origin));
6999
+ }
7000
+ if (request.method !== "POST") return reply(405, errorPage("Method not allowed."));
7001
+ const fetchSite = request.headers["sec-fetch-site"];
7002
+ if (request.headers.origin !== `http://${request.headers.host}` || fetchSite !== void 0 && fetchSite !== "same-origin") return reply(403, errorPage("Allow sites from the Tencil page itself."));
7003
+ const body = await readBody(request, 4096).catch(() => void 0);
7004
+ if (body === void 0) return;
7005
+ const origin = approvableOrigin(new URLSearchParams(body).get("origin"));
7006
+ if (!origin) return reply(400, errorPage("That is not a site Tencil can allow."));
7007
+ allowedOrigins.add(origin);
7008
+ log(`Allowed ${origin} to connect`);
7009
+ reply(200, allowedPage(origin));
7010
+ };
6634
7011
  const wss = new WebSocketServer({
6635
7012
  noServer: true,
6636
7013
  maxPayload: MAX_PAYLOAD_BYTES
6637
7014
  });
6638
7015
  const handleUpgrade = (request, socket, head) => {
6639
- if (new URL(request.url ?? "/", "http://localhost").pathname !== "/ws" || !isAllowedHost(request, knownHosts) || !isAllowedOrigin(request, allowedOrigins)) {
7016
+ const url = new URL(request.url ?? "/", "http://localhost");
7017
+ const refuse = () => {
6640
7018
  socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
6641
7019
  socket.destroy();
6642
- return;
7020
+ };
7021
+ if (url.pathname !== "/ws" || !isAllowedHost(request, knownHosts)) return refuse();
7022
+ if (!isAllowedOrigin(request, allowedOrigins.all())) {
7023
+ const origin = approvableOrigin(request.headers.origin);
7024
+ if (!origin) return refuse();
7025
+ return wss.handleUpgrade(request, socket, head, (ws) => {
7026
+ const approveUrl = `http://${request.headers.host}/allow?origin=${encodeURIComponent(origin)}`;
7027
+ ws.send(JSON.stringify({
7028
+ type: "origin.blocked",
7029
+ origin,
7030
+ approveUrl
7031
+ }));
7032
+ ws.close(4003, "Origin not allowed");
7033
+ });
6643
7034
  }
6644
7035
  wss.handleUpgrade(request, socket, head, (ws) => serveClient(ws));
6645
7036
  };
@@ -6836,5 +7227,21 @@ function resolveOverlayPath() {
6836
7227
  ];
6837
7228
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
6838
7229
  }
7230
+ /** A small request body, refused past `limit` bytes. */
7231
+ function readBody(request, limit) {
7232
+ return new Promise((resolveBody, reject) => {
7233
+ let body = "";
7234
+ request.setEncoding("utf8");
7235
+ request.on("data", (chunk) => {
7236
+ body += chunk;
7237
+ if (body.length > limit) {
7238
+ reject(/* @__PURE__ */ new Error("Request body too large"));
7239
+ request.destroy();
7240
+ }
7241
+ });
7242
+ request.on("end", () => resolveBody(body));
7243
+ request.on("error", reject);
7244
+ });
7245
+ }
6839
7246
  //#endregion
6840
7247
  export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E, EnsembleCredentialStore as F, EnsembleClient as I, Bridge as L, loadAgentSdk as M, ProjectResolver as N, exchangePairingCredential as O, projectRoot as P, renderPrompt as R, defaultDataDir as S, CredentialStore as T, detectAgents as _, readPlan as a, savedProvider as b, runtimeDir as c, uninstallService as d, startInBackground as f, PROVIDERS as g, updateNotice as h, finishUpdate as i, codexProblem as j, parsePairingInput as k, isServiceInstalled as l, isNewerThanThis as m, probeDaemon as n, enableAutostart as o, stopDaemon as p, startDaemon as r, ensureDaemon as s, DEFAULT_PORT as t, stopService as u, providerLabel as v, VERSION as w, FileThreadStore as x, saveProvider as y, stripContext as z };