@connextar/house 0.28.0 → 0.29.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.
Files changed (50) hide show
  1. package/README.md +55 -11
  2. package/dist/ai/index.d.ts +1 -1
  3. package/dist/ai/index.d.ts.map +1 -1
  4. package/dist/ai/index.js +1 -1
  5. package/dist/ai/index.js.map +1 -1
  6. package/dist/ai/pricing.d.ts.map +1 -1
  7. package/dist/ai/pricing.js +9 -4
  8. package/dist/ai/pricing.js.map +1 -1
  9. package/dist/ai/provider.d.ts +17 -5
  10. package/dist/ai/provider.d.ts.map +1 -1
  11. package/dist/ai/provider.js +20 -3
  12. package/dist/ai/provider.js.map +1 -1
  13. package/dist/analytics/browser.d.ts +13 -2
  14. package/dist/analytics/browser.d.ts.map +1 -1
  15. package/dist/analytics/browser.js +93 -8
  16. package/dist/analytics/browser.js.map +1 -1
  17. package/dist/analytics/config.d.ts +5 -0
  18. package/dist/analytics/config.d.ts.map +1 -1
  19. package/dist/analytics/config.js +5 -0
  20. package/dist/analytics/config.js.map +1 -1
  21. package/dist/analytics/index.d.ts +1 -1
  22. package/dist/analytics/index.d.ts.map +1 -1
  23. package/dist/analytics/index.js +1 -1
  24. package/dist/analytics/index.js.map +1 -1
  25. package/dist/analytics/react.d.ts +5 -1
  26. package/dist/analytics/react.d.ts.map +1 -1
  27. package/dist/analytics/react.js +9 -4
  28. package/dist/analytics/react.js.map +1 -1
  29. package/dist/analytics/server-index.d.ts +1 -1
  30. package/dist/analytics/server-index.d.ts.map +1 -1
  31. package/dist/analytics/server-index.js.map +1 -1
  32. package/dist/analytics/server.d.ts +19 -7
  33. package/dist/analytics/server.d.ts.map +1 -1
  34. package/dist/analytics/server.js +25 -10
  35. package/dist/analytics/server.js.map +1 -1
  36. package/dist/voice/relay/model.d.ts +4 -1
  37. package/dist/voice/relay/model.d.ts.map +1 -1
  38. package/dist/voice/relay/model.js +7 -2
  39. package/dist/voice/relay/model.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/ai/index.ts +1 -0
  42. package/src/ai/pricing.ts +16 -4
  43. package/src/ai/provider.ts +31 -7
  44. package/src/analytics/browser.ts +99 -8
  45. package/src/analytics/config.ts +5 -0
  46. package/src/analytics/index.ts +1 -0
  47. package/src/analytics/react.tsx +9 -4
  48. package/src/analytics/server-index.ts +1 -0
  49. package/src/analytics/server.ts +52 -14
  50. package/src/voice/relay/model.ts +17 -3
package/src/ai/pricing.ts CHANGED
@@ -38,14 +38,23 @@ const anthropic = (model: string, input: number, output: number): ModelPrice =>
38
38
  source: ANTHROPIC_SOURCE,
39
39
  });
40
40
 
41
- const openai = (model: string, input: number, output: number): ModelPrice => ({
41
+ const OPENAI_GPT6_SOURCE =
42
+ "OpenAI API pricing, checked 2026-11-25 — cached input and cache writes as published per model";
43
+
44
+ /** OpenAI's gpt-5 rule by default; a model with its own published cache rates passes them. */
45
+ const openai = (
46
+ model: string,
47
+ input: number,
48
+ output: number,
49
+ cache?: { read: number; write: number; source: string },
50
+ ): ModelPrice => ({
42
51
  provider: "OPENAI",
43
52
  model,
44
53
  inputPerMillionUsd: input,
45
54
  outputPerMillionUsd: output,
46
- cacheReadPerMillionUsd: input * 0.1,
47
- cacheWritePerMillionUsd: input,
48
- source: OPENAI_SOURCE,
55
+ cacheReadPerMillionUsd: cache?.read ?? input * 0.1,
56
+ cacheWritePerMillionUsd: cache?.write ?? input,
57
+ source: cache?.source ?? OPENAI_SOURCE,
49
58
  });
50
59
 
51
60
  /**
@@ -61,6 +70,9 @@ export const DEFAULT_PRICES: readonly ModelPrice[] = Object.freeze([
61
70
  anthropic("claude-sonnet-4-6", 3, 15),
62
71
  openai("gpt-5", 1.25, 10),
63
72
  openai("gpt-5-mini", 0.25, 2),
73
+ openai("gpt-6.1-sol", 2, 10, { read: 0.1, write: 2.5, source: OPENAI_GPT6_SOURCE }),
74
+ openai("gpt-6.1-terra", 1, 5, { read: 0.05, write: 1.25, source: OPENAI_GPT6_SOURCE }),
75
+ openai("gpt-6-luna", 0.1, 0.5, { read: 0.01, write: 0.125, source: OPENAI_GPT6_SOURCE }),
64
76
  ]);
65
77
 
66
78
  /**
@@ -99,15 +99,38 @@ export class AiUnusableAnswerError extends AiUnavailableError {
99
99
  * How hard an OpenAI reasoning model thinks before it answers (0.17.0).
100
100
  * Its thinking is billed as output and shares `maxTokens`, so a job that is
101
101
  * reading and listing rather than solving can save most of its time and cost
102
- * with `"low"`. Sent only to models that reason — the gpt-5 family (not its
103
- * `-chat` models) and the o-series — so a non-reasoning model an operator
104
- * chooses still works. Anthropic ignores it; it has `thinking` and `effort`.
102
+ * with `"low"`. Sent only to models that reason — the gpt-5 and gpt-6 families
103
+ * (not their `-chat` models) and the o-series — so a non-reasoning model an
104
+ * operator chooses still works. Anthropic ignores it; it has `thinking` and `effort`.
105
+ *
106
+ * Which levels a model takes differs by model (0.28.1): the gpt-6 family takes
107
+ * no `"minimal"`, and gpt-6.1-sol no `"none"` either; OpenAI's migration advice
108
+ * is `"low"` instead, and that is what such a model is sent
109
+ * (`openAiReasoningEffortFor`). `"none"`, `"xhigh"` and `"max"` are for the
110
+ * models that take them; an older model is sent what was asked for.
105
111
  */
106
- export type OpenAiReasoningEffort = "minimal" | "low" | "medium" | "high";
112
+ export type OpenAiReasoningEffort = "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
107
113
 
108
114
  /** Whether an OpenAI model takes a reasoning effort. By name: the API has no way to ask. */
109
115
  export function takesReasoningEffort(model: string): boolean {
110
- return /^(gpt-5|o\d)/.test(model) && !/-chat/.test(model);
116
+ return /^(gpt-[56]\b|o\d)/.test(model) && !/-chat/.test(model);
117
+ }
118
+
119
+ /**
120
+ * The effort to send an OpenAI model, or undefined to send none: nothing was
121
+ * asked for, or the model doesn't reason. A level the gpt-6 family refuses is
122
+ * sent as `"low"`, OpenAI's advice for moving off `"minimal"` and `"none"`.
123
+ */
124
+ export function openAiReasoningEffortFor(
125
+ model: string,
126
+ effort: OpenAiReasoningEffort | null | undefined,
127
+ ): OpenAiReasoningEffort | undefined {
128
+ if (!effort || !takesReasoningEffort(model)) return undefined;
129
+ if (/^gpt-6\b/.test(model)) {
130
+ if (effort === "minimal") return "low";
131
+ if (effort === "none" && /-sol\b/.test(model)) return "low";
132
+ }
133
+ return effort;
111
134
  }
112
135
 
113
136
  export interface AiCallResult {
@@ -211,7 +234,8 @@ function anthropicUsage(provider: AiProviderName, message: Anthropic.Message): A
211
234
 
212
235
  /** The `reasoning` field for an OpenAI request, or nothing when the model doesn't reason or none was asked for. */
213
236
  function openAiReasoning(model: string, effort: OpenAiReasoningEffort | undefined) {
214
- return effort && takesReasoningEffort(model) ? { reasoning: { effort } } : {};
237
+ const sent = openAiReasoningEffortFor(model, effort);
238
+ return sent ? { reasoning: { effort: sent } } : {};
215
239
  }
216
240
 
217
241
  export interface AiHarnessOptions<Task extends string> {
@@ -242,7 +266,7 @@ export interface AiHarness<Task extends string> {
242
266
  * tasks: {
243
267
  * categorise: {
244
268
  * ANTHROPIC: { modelVar: "ANTHROPIC_MODEL", defaultModel: "claude-haiku-4-5-20251001" },
245
- * OPENAI: { modelVar: "OPENAI_MODEL", defaultModel: "gpt-5-mini" },
269
+ * OPENAI: { modelVar: "OPENAI_MODEL", defaultModel: "gpt-6.1-terra" },
246
270
  * },
247
271
  * },
248
272
  * });
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ACCOUNT_ATTRIBUTE,
2
3
  CONSENT_KNOWN_ATTRIBUTE,
3
4
  NOT_MEASURED_ATTRIBUTE,
4
5
  RECORDABLE_ATTRIBUTE,
@@ -22,8 +23,13 @@ import {
22
23
  * `recordablePath` with `<RecordingAllowed />` on it; and never while `ViewingAsBanner` or a `data-analytics-private`
23
24
  * marker is on the page.
24
25
  * - **One gate, deny by default** (`before_send`): every address cleaned, heatmaps only for this page, replay's
25
- * addresses cleaned, dead-click text stripped, an exception redacted whole. No feature flags, so no `/flags` request
26
+ * addresses cleaned, dead-click text stripped, an exception redacted whole, no person properties. No feature flags, so no `/flags` request
26
27
  * carrying the first page's full address.
28
+ * - **Identified only by an internal id, only after a yes** (0.29.0). A page the app marks with the signed-in member's
29
+ * id (`<RecordingAllowed account={id} />`) tags its error reports with that id, as the distinct id and nothing
30
+ * else, with no person profile. Once they have said yes, on a page that is measured, PostHog identifies them by it
31
+ * (`syncIdentity`); a no, a view, an opt-out, a different account or an unmeasured page without the mark resets
32
+ * it, and so does signing out (`forgetAccount`). Nothing is stored: each page load identifies again from the page.
27
33
  */
28
34
 
29
35
  export type AnalyticsConsent = "granted" | "denied";
@@ -44,6 +50,9 @@ export interface PostHogLike {
44
50
  stopSessionRecording(): void;
45
51
  captureException(error: unknown, properties?: Record<string, unknown>): unknown;
46
52
  heatmaps?: { getAndClearBuffer(): unknown } | null;
53
+ /** For `syncIdentity` and `forgetAccount` (0.29.0); a PostHog without them is never identified. */
54
+ identify?(distinctId: string): void;
55
+ reset?(): void;
47
56
  }
48
57
 
49
58
  export interface BrowserAnalyticsOptions {
@@ -61,6 +70,8 @@ const SCRIPT_ID = "gtm-script";
61
70
  const RRWEB_META = 4;
62
71
  const RRWEB_CUSTOM = 5;
63
72
  const URL_PROPERTY = /url|pathname|referrer|href/i;
73
+ /** An internal id: a cuid, a UUID, Better Auth's 32 characters. Never an email (no `@`), never a name (no spaces). */
74
+ const ACCOUNT_ID = /^[A-Za-z0-9_-]{8,64}$/;
64
75
 
65
76
  export type BrowserAnalytics = ReturnType<typeof createBrowserAnalytics>;
66
77
 
@@ -70,6 +81,10 @@ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAna
70
81
  const consentListeners = new Set<() => void>();
71
82
  const recordableListeners = new Set<() => void>();
72
83
  let measuring = false;
84
+ /** Who PostHog is identified as in this document, by `syncIdentity`. Memory only, like PostHog's own. */
85
+ let identifiedAs: string | null = null;
86
+ /** Signed out of while the page still carries their mark: not identified again until the mark has gone. */
87
+ let signedOutOf: string | null = null;
73
88
 
74
89
  // ── Consent ──────────────────────────────────────────────────────────────
75
90
 
@@ -210,6 +225,17 @@ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAna
210
225
 
211
226
  // ── PostHog ──────────────────────────────────────────────────────────────
212
227
 
228
+ /**
229
+ * The signed-in member this page is for, from `<RecordingAllowed account>` — or null: no mark, a malformed one, a
230
+ * page marked private or a view. Not consent: error reports carry it for everyone.
231
+ */
232
+ function pageAccount(): string | null {
233
+ if (pageIsPrivate()) return null;
234
+ const value = win().document.querySelector(`[${ACCOUNT_ATTRIBUTE}]`)?.getAttribute(ACCOUNT_ATTRIBUTE) ?? "";
235
+ if (!ACCOUNT_ID.test(value) || value === signedOutOf) return null;
236
+ return value;
237
+ }
238
+
213
239
  function pageIsRecordable(): boolean {
214
240
  return marked(RECORDABLE_ATTRIBUTE);
215
241
  }
@@ -306,17 +332,37 @@ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAna
306
332
  // rest redacted. Redaction alone kept another site's full path and this page's query names and fragment, on
307
333
  // the one event sent without a yes (AltEd round 39, A-2).
308
334
  cleanProperties(event.properties);
309
- cleanProperties(event.$set);
310
- cleanProperties(event.$set_once);
311
- return analytics.redactDeep(event);
335
+ dropPersonProperties(event);
336
+ return tagAccount(analytics.redactDeep(event));
312
337
  }
313
338
  if (!measuredHere()) return null;
314
339
  if (event.event === "$$heatmap" && !cleanHeatmap(event)) return null;
315
340
  if (event.event === "$snapshot") cleanSnapshot(event);
316
341
  if (event.event === "$dead_click" || event.event === "$dead_swipe") cleanDeadClick(event);
317
342
  cleanProperties(event.properties);
318
- cleanProperties(event.$set);
319
- cleanProperties(event.$set_once);
343
+ dropPersonProperties(event);
344
+ return event;
345
+ }
346
+
347
+ /**
348
+ * No person properties, ever (0.29.0): a person is their internal id and nothing else. posthog-js adds its own to
349
+ * `$identify` — the first page, referrer and campaign as `$set_once` — and the gate drops them, cleaned or not.
350
+ */
351
+ function dropPersonProperties(event: CaptureResult): void {
352
+ delete event.$set;
353
+ delete event.$set_once;
354
+ }
355
+
356
+ /**
357
+ * An error report from a page marked with a member's id carries it as the distinct id, consent or not — the id and
358
+ * nothing else, and no person profile unless they are identified already. Added after redaction, which must not
359
+ * touch it.
360
+ */
361
+ function tagAccount<T extends CaptureResult>(event: T): T {
362
+ const account = pageAccount();
363
+ if (!account || !event.properties) return event;
364
+ event.properties.distinct_id = account;
365
+ if (identifiedAs !== account) event.properties.$process_person_profile = false;
320
366
  return event;
321
367
  }
322
368
 
@@ -326,7 +372,9 @@ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAna
326
372
  api_host: overrides.apiHost ?? "/ingest",
327
373
  ui_host: overrides.uiHost ?? "https://eu.posthog.com",
328
374
  persistence: "memory" as const,
329
- person_profiles: "never" as const,
375
+ // A person only once `syncIdentity` identifies one — after a yes, by an id the page carries. Until then, and for
376
+ // an app that never marks an account, every event is personless, as "never" made it.
377
+ person_profiles: "identified_only" as const,
330
378
  capture_exceptions: true,
331
379
  capture_pageview: "history_change" as const,
332
380
  capture_pageleave: "if_capture_pageview" as const,
@@ -378,7 +426,47 @@ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAna
378
426
  }
379
427
  }
380
428
 
381
- /** A handled error from the browser: anonymous and redacted by the gate, consent or not. */
429
+ /**
430
+ * Identify, or stop identifying, as consent and the page change; call it before `syncRecording`, which
431
+ * `<SiteAnalytics>` does. Identified only while the page carries a member's id and is measured — so after a yes,
432
+ * never during a view or for an opted-out browser — and by the id alone. Reset when they say no, opt out, a view
433
+ * starts, the page names a different account, or they reach an unmeasured page without the mark (signed out, a
434
+ * learner's page). A public page keeps it: the same person, still in the same document.
435
+ */
436
+ function syncIdentity(posthog: PostHogLike | null | undefined): void {
437
+ if (!posthog?.__loaded || !posthog.identify || !posthog.reset) return;
438
+ const marked = win().document.querySelector(`[${ACCOUNT_ATTRIBUTE}]`) !== null;
439
+ if (!marked) signedOutOf = null;
440
+ const account = pageAccount();
441
+ const measured = measuredHere();
442
+ if (identifiedAs) {
443
+ const refused = readConsent() !== "granted" || browserOptsOut() || pageIsPrivate();
444
+ const otherAccount = account !== null && account !== identifiedAs;
445
+ const unmarkedPrivatePage = !account && !analytics.isTaggedPath(win().location.pathname);
446
+ if (refused || otherAccount || unmarkedPrivatePage) {
447
+ posthog.reset();
448
+ identifiedAs = null;
449
+ }
450
+ }
451
+ if (account && measured && identifiedAs !== account) {
452
+ posthog.identify(account);
453
+ identifiedAs = account;
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Signing out: PostHog starts again as nobody, so the next person on a shared computer is never merged with this
459
+ * one. Reset whether or not they were identified — an anonymous trail is theirs too.
460
+ */
461
+ function forgetAccount(posthog: PostHogLike | null | undefined): void {
462
+ // Only the mark on this page is held back: signing in again elsewhere brings a fresh one.
463
+ const account = pageAccount();
464
+ if (account) signedOutOf = account;
465
+ identifiedAs = null;
466
+ if (posthog?.__loaded) posthog.reset?.();
467
+ }
468
+
469
+ /** A handled error from the browser: redacted by the gate, consent or not, and tagged with the page's account. */
382
470
  function reportError(posthog: PostHogLike | null | undefined, error: unknown, properties?: Record<string, unknown>) {
383
471
  if (posthog?.__loaded) posthog.captureException(error, properties);
384
472
  }
@@ -402,9 +490,12 @@ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAna
402
490
  subscribeToRecordable,
403
491
  recordableChanged,
404
492
  measuredHere,
493
+ pageAccount,
405
494
  gate,
406
495
  posthogConfig,
407
496
  syncRecording,
497
+ syncIdentity,
498
+ forgetAccount,
408
499
  reportError,
409
500
  /** Ask again: what a footer's "Cookie settings" does. */
410
501
  reopenConsent: () => win().dispatchEvent(new Event(analytics.cookieSettingsEvent)),
@@ -53,6 +53,11 @@ export const NOT_MEASURED_ATTRIBUTE = "data-analytics-private";
53
53
  export const VIEWING_AS_ATTRIBUTE = "data-viewing-as";
54
54
  /** Rendered by `<RecordingAllowed />` on a signed-in page the app lets be measured. */
55
55
  export const RECORDABLE_ATTRIBUTE = "data-analytics-recordable";
56
+ /**
57
+ * Rendered by `<RecordingAllowed account={id} />`: the signed-in member's internal id — never an email or a name. Error
58
+ * reports from the page carry it, and after a yes PostHog identifies them by it (0.29.0).
59
+ */
60
+ export const ACCOUNT_ATTRIBUTE = "data-analytics-account";
56
61
  /** Set before paint once an answer is known, so the card is hidden by CSS and never flashes. */
57
62
  export const CONSENT_KNOWN_ATTRIBUTE = "data-consent-known";
58
63
 
@@ -5,6 +5,7 @@
5
5
  * error reports included, is `/analytics/server`.
6
6
  */
7
7
  export {
8
+ ACCOUNT_ATTRIBUTE,
8
9
  CONSENT_KNOWN_ATTRIBUTE,
9
10
  NOT_MEASURED_ATTRIBUTE,
10
11
  RECORDABLE_ATTRIBUTE,
@@ -5,7 +5,7 @@ import * as React from "react";
5
5
 
6
6
  import { cx } from "../internal/cx.js";
7
7
  import type { AnalyticsConsent, BrowserAnalytics, PostHogLike } from "./browser.js";
8
- import { NOT_MEASURED_ATTRIBUTE, RECORDABLE_ATTRIBUTE } from "./config.js";
8
+ import { ACCOUNT_ATTRIBUTE, NOT_MEASURED_ATTRIBUTE, RECORDABLE_ATTRIBUTE } from "./config.js";
9
9
 
10
10
  /**
11
11
  * The components: the cookie card and everything it drives, the pre-paint script, the "Cookie settings" button, the
@@ -100,6 +100,8 @@ export function SiteAnalytics({
100
100
  }, [browser, containerId, consent, tagged, optedOut]);
101
101
 
102
102
  React.useEffect(() => {
103
+ // Identity first: a reset starts a new session, which replay must start in.
104
+ browser.syncIdentity(posthog);
103
105
  browser.syncRecording(posthog);
104
106
  }, [browser, posthog, consent, pathname, recordable]);
105
107
 
@@ -202,16 +204,19 @@ export function CookieSettingsButton({
202
204
  /**
203
205
  * On a signed-in page the app lets be measured (`recordablePath`), for an ordinary member: render it for them, and
204
206
  * never for an administrator or during a view. Without it the page is not measured.
207
+ *
208
+ * `account` (0.29.0) is the member's internal id — never an email or a name. Error reports from the page carry it, and
209
+ * after a yes PostHog identifies them by it (`syncIdentity`). Leave it out and nobody is identified.
205
210
  */
206
- export function RecordingAllowed({ browser }: { browser: BrowserAnalytics }) {
211
+ export function RecordingAllowed({ browser, account }: { browser: BrowserAnalytics; account?: string }) {
207
212
  React.useEffect(() => {
208
213
  browser.recordableChanged();
209
214
  return () => {
210
215
  // After unmount the marker is gone; tell the listeners on the next tick, when the DOM says so.
211
216
  queueMicrotask(() => browser.recordableChanged());
212
217
  };
213
- }, [browser]);
214
- return <span hidden {...{ [RECORDABLE_ATTRIBUTE]: "" }} />;
218
+ }, [browser, account]);
219
+ return <span hidden {...{ [RECORDABLE_ATTRIBUTE]: "", ...(account ? { [ACCOUNT_ATTRIBUTE]: account } : {}) }} />;
215
220
  }
216
221
 
217
222
  /**
@@ -8,6 +8,7 @@ export {
8
8
  readGaCookies,
9
9
  registeredErrorReporter,
10
10
  signUpMethod,
11
+ type ErrorRequest,
11
12
  type GaCookies,
12
13
  type MeasurementProtocolOptions,
13
14
  type PostHogServerLike,
@@ -6,9 +6,9 @@ import type { Analytics } from "./config.js";
6
6
  * Imports no browser package, no PostHog and no Next: the app passes its `posthog-node` client (`posthog`) and Next's
7
7
  * `after` (`after`), so this runs wherever the app's server code does and the versions stay the app's.
8
8
  *
9
- * - **Errors** — `onRequestError` and the handled 500s — are sent anonymous (no distinct id, no person profile),
10
- * with the message and every stack frame redacted, and a Prisma error reduced to its code: a Prisma message quotes
11
- * the query's values. Quickie's frames are taken only after the original `name: message` head, so a message line that
9
+ * - **Errors** — `onRequestError` and the handled 500s — are sent with no person profile, keyed by the signed-in
10
+ * member's internal id when the app's `accountId` names one (0.29.0) and anonymous otherwise, with the message and
11
+ * every stack frame redacted, and a Prisma error reduced to its code: a Prisma message quotes the query's values. Quickie's frames are taken only after the original `name: message` head, so a message line that
12
12
  * looks like ` at 12 High Street` cannot pass as a frame. AltEd reduced nothing and redacted only tokens.
13
13
  * - **Events** keyed by a person are refused while viewing as somebody (senco's rule — Quickie's had none) and for a
14
14
  * request that sends `Sec-GPC: 1`, and their properties are redacted.
@@ -36,12 +36,28 @@ export interface ServerAnalyticsOptions {
36
36
  isViewingAs?: () => boolean | Promise<boolean>;
37
37
  /** The request's headers, for `Sec-GPC`: Next's `headers`. Outside a request, return null. */
38
38
  requestHeaders?: () => Pick<Headers, "get"> | null | undefined | Promise<Pick<Headers, "get"> | null | undefined>;
39
+ /**
40
+ * The signed-in member a request is for, by internal id — never an email or a name — or null for anyone the app
41
+ * does not identify (a learner, an administrator, a view, nobody). Error reports carry it as their distinct id
42
+ * (0.29.0). `request` is `onRequestError`'s, whose headers are the request's; for a handled 500 there is none, and
43
+ * Next's `headers()` still answers. Fail-closed: a lookup that throws, or answers something that is not an id, sends
44
+ * the report anonymous.
45
+ */
46
+ accountId?: (request?: ErrorRequest) => string | null | undefined | Promise<string | null | undefined>;
39
47
  /** Next's `after`, to send once the response has gone. Default: sent at once, not awaited. */
40
48
  after?: (task: () => Promise<void>) => void;
41
49
  logger?: { error(message: string, ...detail: unknown[]): void };
42
50
  }
43
51
 
52
+ /** What `onRequestError` is handed about the request. */
53
+ export interface ErrorRequest {
54
+ method?: string;
55
+ path?: string;
56
+ headers?: Record<string, string | string[] | undefined>;
57
+ }
58
+
44
59
  const MESSAGE_LIMIT = 1000;
60
+ const ACCOUNT_ID = /^[A-Za-z0-9_-]{8,64}$/;
45
61
  const FRAME = /^\s+at /;
46
62
 
47
63
  export type ServerAnalytics = ReturnType<typeof createServerAnalytics>;
@@ -76,11 +92,30 @@ export function createServerAnalytics(options: ServerAnalyticsOptions) {
76
92
  return copy;
77
93
  }
78
94
 
79
- async function reportServerError(error: unknown, properties: Record<string, unknown> = {}): Promise<void> {
95
+ async function account(request?: ErrorRequest): Promise<string | undefined> {
96
+ try {
97
+ const id = await options.accountId?.(request);
98
+ return typeof id === "string" && ACCOUNT_ID.test(id) ? id : undefined;
99
+ } catch {
100
+ return undefined;
101
+ }
102
+ }
103
+
104
+ /** An error report, keyed by the account of `request` (or of the request in scope) when the app names one. */
105
+ async function reportServerError(
106
+ error: unknown,
107
+ properties: Record<string, unknown> = {},
108
+ request?: ErrorRequest,
109
+ ): Promise<void> {
110
+ if (!options.posthog()) return;
111
+ await send(error, properties, await account(request));
112
+ }
113
+
114
+ async function send(error: unknown, properties: Record<string, unknown>, distinctId: string | undefined) {
80
115
  const posthog = options.posthog();
81
116
  if (!posthog) return;
82
117
  try {
83
- await posthog.captureExceptionImmediate(redactedError(error), undefined, {
118
+ await posthog.captureExceptionImmediate(redactedError(error), distinctId, {
84
119
  ...analytics.redactDeep(properties),
85
120
  $process_person_profile: false,
86
121
  });
@@ -101,24 +136,27 @@ export function createServerAnalytics(options: ServerAnalyticsOptions) {
101
136
  void task();
102
137
  }
103
138
 
104
- /** For `handleError`'s 500s: sent once the response has gone. */
139
+ /**
140
+ * For `handleError`'s 500s: sent once the response has gone. The account is looked up now, while the request's
141
+ * headers are still in scope — Next allows `headers()` inside `after` only in route handlers and server actions.
142
+ */
105
143
  function reportServerErrorAfterResponse(error: unknown, properties: Record<string, unknown> = {}): void {
106
144
  if (!options.posthog()) return;
107
- later(() => reportServerError(error, properties));
145
+ const id = account();
146
+ later(async () => send(error, properties, await id));
108
147
  }
109
148
 
110
149
  /** `export const onRequestError = server.onRequestError` in `instrumentation.ts`: the route pattern, never the URL. */
111
150
  async function onRequestError(
112
151
  error: unknown,
113
- request: { method?: string },
152
+ request: ErrorRequest,
114
153
  context: { routePath?: string; routeType?: string },
115
154
  ): Promise<void> {
116
- await reportServerError(error, {
117
- source: "server",
118
- route: context.routePath,
119
- route_type: context.routeType,
120
- method: request.method,
121
- });
155
+ await reportServerError(
156
+ error,
157
+ { source: "server", route: context.routePath, route_type: context.routeType, method: request.method },
158
+ request,
159
+ );
122
160
  }
123
161
 
124
162
  async function refused(): Promise<boolean> {
@@ -5,7 +5,12 @@ import type { MessageStream } from "@anthropic-ai/sdk/lib/MessageStream";
5
5
  import OpenAI from "openai";
6
6
 
7
7
  import { PROVIDER_LABELS, type AiProviderName, type ResolvedAi } from "../../ai/config.js";
8
- import { AiServiceError, OPENAI_MIN_OUTPUT_TOKENS, type AiCallResult } from "../../ai/provider.js";
8
+ import {
9
+ AiServiceError,
10
+ OPENAI_MIN_OUTPUT_TOKENS,
11
+ openAiReasoningEffortFor,
12
+ type AiCallResult,
13
+ } from "../../ai/provider.js";
9
14
  import { TransferLineStream } from "./transfer-line.js";
10
15
 
11
16
  /**
@@ -74,7 +79,10 @@ export interface DialogModel {
74
79
  /** The resolved provider, key and model, how long a reply may run, and the app's tools. */
75
80
  export interface DialogModelOptions extends ResolvedAi {
76
81
  maxTokens?: number;
77
- /** How hard an OpenAI reasoning model thinks before it speaks. Sent only when set. */
82
+ /**
83
+ * How hard an OpenAI reasoning model thinks before it speaks. Sent only when set, and only
84
+ * to a model that reasons; a level the model refuses is mapped (`openAiReasoningEffortFor`).
85
+ */
78
86
  reasoningEffort?: OpenAI.ReasoningEffort;
79
87
  /** How hard a current Claude model thinks before it speaks. Sent only when set. */
80
88
  anthropicEffort?: Anthropic.OutputConfig["effort"];
@@ -271,6 +279,12 @@ function createAnthropicModel(opts: DialogModelOptions): DialogModel {
271
279
  };
272
280
  }
273
281
 
282
+ /** The `reasoning` field for the model, or nothing: see `openAiReasoningEffortFor`. */
283
+ function reasoningFor(opts: DialogModelOptions) {
284
+ const effort = openAiReasoningEffortFor(opts.model, opts.reasoningEffort);
285
+ return effort ? { reasoning: { effort } } : {};
286
+ }
287
+
274
288
  function createOpenAiModel(opts: DialogModelOptions): DialogModel {
275
289
  const client = new OpenAI({ apiKey: opts.apiKey });
276
290
  const toolsFor = memo((team) => openAiTools(opts.tools(team)));
@@ -288,7 +302,7 @@ function createOpenAiModel(opts: DialogModelOptions): DialogModel {
288
302
  input: toResponsesInput(messages),
289
303
  tools: toolsFor(team ?? "open"),
290
304
  max_output_tokens: Math.max(opts.maxTokens ?? DEFAULT_MAX_TOKENS, OPENAI_MIN_OUTPUT_TOKENS),
291
- ...(opts.reasoningEffort ? { reasoning: { effort: opts.reasoningEffort } } : {}),
305
+ ...reasoningFor(opts),
292
306
  // A call's words are personal data: OpenAI keeps none of it for us.
293
307
  store: false,
294
308
  },