@reticlehq/core 2.4.0 → 2.6.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 (46) hide show
  1. package/dist/consequence.d.ts +27 -0
  2. package/dist/consequence.js +26 -0
  3. package/dist/constants.d.ts +68 -0
  4. package/dist/constants.js +65 -0
  5. package/dist/contract-fingerprint.d.ts +29 -0
  6. package/dist/contract-fingerprint.js +56 -0
  7. package/dist/daemon-registry.js +1 -1
  8. package/dist/event-classification.d.ts +7 -0
  9. package/dist/event-classification.js +15 -0
  10. package/dist/event-payloads.d.ts +48 -0
  11. package/dist/event-payloads.js +12 -1
  12. package/dist/flow-constants.d.ts +8 -0
  13. package/dist/flow-constants.js +12 -0
  14. package/dist/flow-types.d.ts +23 -0
  15. package/dist/index.d.ts +3 -0
  16. package/dist/index.js +3 -0
  17. package/dist/journal.d.ts +2 -2
  18. package/dist/messages.d.ts +48 -0
  19. package/dist/messages.js +20 -0
  20. package/dist/net.d.ts +40 -0
  21. package/dist/net.js +44 -0
  22. package/dist/project-id.d.ts +28 -0
  23. package/dist/project-id.js +51 -0
  24. package/dist/redaction.js +4 -4
  25. package/dist/schema/hello-message.json +8 -0
  26. package/dist/schema/reticle-message.json +8 -0
  27. package/dist/security.js +10 -5
  28. package/dist/source-constants.d.ts +6 -0
  29. package/dist/source-constants.js +6 -0
  30. package/dist/state-select.d.ts +14 -2
  31. package/dist/state-select.js +77 -14
  32. package/dist/telemetry-feedback.d.ts +32 -10
  33. package/dist/telemetry-feedback.js +21 -0
  34. package/dist/telemetry-session.d.ts +169 -0
  35. package/dist/telemetry-session.js +139 -0
  36. package/dist/telemetry.d.ts +706 -92
  37. package/dist/telemetry.js +251 -4
  38. package/dist/toon.d.ts +2 -1
  39. package/dist/toon.js +37 -37
  40. package/dist/types.d.ts +48 -0
  41. package/dist/types.js +12 -0
  42. package/dist/upgrade.js +1 -1
  43. package/dist/verification-run.d.ts +28 -28
  44. package/dist/verified-constants.d.ts +53 -0
  45. package/dist/verified-constants.js +52 -0
  46. package/package.json +5 -3
@@ -179,6 +179,26 @@ export declare const HelloMessageSchema: z.ZodObject<{
179
179
  token: z.ZodOptional<z.ZodString>;
180
180
  /** Whether the app has advertised a capability registry (reticle.describe). */
181
181
  hasCapabilities: z.ZodOptional<z.ZodBoolean>;
182
+ /**
183
+ * The version of the SDK in the page, so a version-skewed pair can SAY so.
184
+ *
185
+ * `protocolVersion` only catches an incompatible wire format. A 2.2.1 SDK against a 2.4.0 daemon
186
+ * agrees on the protocol, connects fine, and then disagrees about tool behaviour — which surfaced
187
+ * as a bare `-32000` with nothing on either side naming a version. Supplied by the build plugin
188
+ * (which can read the installed package's version Node-side); absent means "unknown", never
189
+ * "matching", so a hand-wired connect is not falsely reported as in sync.
190
+ */
191
+ sdkVersion: z.ZodOptional<z.ZodString>;
192
+ /**
193
+ * The wire contract this SDK build speaks (see contract-fingerprint.ts) — DERIVED from core's
194
+ * vocabulary, so it moves only when a name on the wire genuinely changes.
195
+ *
196
+ * `sdkVersion` above answers "which release is this"; this answers the question that actually
197
+ * decides whether the pair works, and it answers it for the two cases a version cannot: a patch
198
+ * bump that changed nothing (equal here → stay quiet) and two different BUILDS of one version
199
+ * number, which is what a stale daemon or a cached npx install is (unequal here → say so).
200
+ */
201
+ contract: z.ZodOptional<z.ZodString>;
182
202
  /**
183
203
  * Extra key names this app declared sensitive via `connect({ redact: { keys } })`.
184
204
  *
@@ -199,6 +219,8 @@ export declare const HelloMessageSchema: z.ZodObject<{
199
219
  projectId?: string | undefined;
200
220
  token?: string | undefined;
201
221
  hasCapabilities?: boolean | undefined;
222
+ sdkVersion?: string | undefined;
223
+ contract?: string | undefined;
202
224
  redactKeys?: string[] | undefined;
203
225
  }, {
204
226
  kind: "hello";
@@ -210,6 +232,8 @@ export declare const HelloMessageSchema: z.ZodObject<{
210
232
  projectId?: string | undefined;
211
233
  token?: string | undefined;
212
234
  hasCapabilities?: boolean | undefined;
235
+ sdkVersion?: string | undefined;
236
+ contract?: string | undefined;
213
237
  redactKeys?: string[] | undefined;
214
238
  }>;
215
239
  export type HelloMessage = z.infer<typeof HelloMessageSchema>;
@@ -380,6 +404,26 @@ export declare const ReticleMessageSchema: z.ZodDiscriminatedUnion<"kind", [z.Zo
380
404
  token: z.ZodOptional<z.ZodString>;
381
405
  /** Whether the app has advertised a capability registry (reticle.describe). */
382
406
  hasCapabilities: z.ZodOptional<z.ZodBoolean>;
407
+ /**
408
+ * The version of the SDK in the page, so a version-skewed pair can SAY so.
409
+ *
410
+ * `protocolVersion` only catches an incompatible wire format. A 2.2.1 SDK against a 2.4.0 daemon
411
+ * agrees on the protocol, connects fine, and then disagrees about tool behaviour — which surfaced
412
+ * as a bare `-32000` with nothing on either side naming a version. Supplied by the build plugin
413
+ * (which can read the installed package's version Node-side); absent means "unknown", never
414
+ * "matching", so a hand-wired connect is not falsely reported as in sync.
415
+ */
416
+ sdkVersion: z.ZodOptional<z.ZodString>;
417
+ /**
418
+ * The wire contract this SDK build speaks (see contract-fingerprint.ts) — DERIVED from core's
419
+ * vocabulary, so it moves only when a name on the wire genuinely changes.
420
+ *
421
+ * `sdkVersion` above answers "which release is this"; this answers the question that actually
422
+ * decides whether the pair works, and it answers it for the two cases a version cannot: a patch
423
+ * bump that changed nothing (equal here → stay quiet) and two different BUILDS of one version
424
+ * number, which is what a stale daemon or a cached npx install is (unequal here → say so).
425
+ */
426
+ contract: z.ZodOptional<z.ZodString>;
383
427
  /**
384
428
  * Extra key names this app declared sensitive via `connect({ redact: { keys } })`.
385
429
  *
@@ -400,6 +444,8 @@ export declare const ReticleMessageSchema: z.ZodDiscriminatedUnion<"kind", [z.Zo
400
444
  projectId?: string | undefined;
401
445
  token?: string | undefined;
402
446
  hasCapabilities?: boolean | undefined;
447
+ sdkVersion?: string | undefined;
448
+ contract?: string | undefined;
403
449
  redactKeys?: string[] | undefined;
404
450
  }, {
405
451
  kind: "hello";
@@ -411,6 +457,8 @@ export declare const ReticleMessageSchema: z.ZodDiscriminatedUnion<"kind", [z.Zo
411
457
  projectId?: string | undefined;
412
458
  token?: string | undefined;
413
459
  hasCapabilities?: boolean | undefined;
460
+ sdkVersion?: string | undefined;
461
+ contract?: string | undefined;
414
462
  redactKeys?: string[] | undefined;
415
463
  }>, z.ZodObject<{
416
464
  kind: z.ZodLiteral<"command">;
package/dist/messages.js CHANGED
@@ -86,6 +86,26 @@ export const HelloMessageSchema = z.object({
86
86
  token: z.string().max(TRANSPORT_LIMITS.MAX_TOKEN_LENGTH).optional(),
87
87
  /** Whether the app has advertised a capability registry (reticle.describe). */
88
88
  hasCapabilities: z.boolean().optional(),
89
+ /**
90
+ * The version of the SDK in the page, so a version-skewed pair can SAY so.
91
+ *
92
+ * `protocolVersion` only catches an incompatible wire format. A 2.2.1 SDK against a 2.4.0 daemon
93
+ * agrees on the protocol, connects fine, and then disagrees about tool behaviour — which surfaced
94
+ * as a bare `-32000` with nothing on either side naming a version. Supplied by the build plugin
95
+ * (which can read the installed package's version Node-side); absent means "unknown", never
96
+ * "matching", so a hand-wired connect is not falsely reported as in sync.
97
+ */
98
+ sdkVersion: z.string().max(TRANSPORT_LIMITS.MAX_ADAPTER_NAME_LENGTH).optional(),
99
+ /**
100
+ * The wire contract this SDK build speaks (see contract-fingerprint.ts) — DERIVED from core's
101
+ * vocabulary, so it moves only when a name on the wire genuinely changes.
102
+ *
103
+ * `sdkVersion` above answers "which release is this"; this answers the question that actually
104
+ * decides whether the pair works, and it answers it for the two cases a version cannot: a patch
105
+ * bump that changed nothing (equal here → stay quiet) and two different BUILDS of one version
106
+ * number, which is what a stale daemon or a cached npx install is (unequal here → say so).
107
+ */
108
+ contract: z.string().max(TRANSPORT_LIMITS.MAX_ADAPTER_NAME_LENGTH).optional(),
89
109
  /**
90
110
  * Extra key names this app declared sensitive via `connect({ redact: { keys } })`.
91
111
  *
package/dist/net.d.ts CHANGED
@@ -39,3 +39,43 @@ export declare const IpcStatus: {
39
39
  * settled, and the server reverted the shipment 1.2s later.
40
40
  */
41
41
  export declare const HTTP_ACCEPTED = 202;
42
+ /**
43
+ * Traffic the DEV TOOLCHAIN makes about itself — never the app under test.
44
+ *
45
+ * A CLOSED list, deliberately. Reported from a real drive: a correct Next.js navigation graded
46
+ * `verified: "no"` because the dev overlay was fetching a source map for an unrelated React key
47
+ * warning (`POST /__nextjs_original-stack-frames`), and that in-flight request counted as "the UI
48
+ * advanced over a request that never settled". Every app that logs one dev warning got a false
49
+ * negative on every action — the worst defect class after a false green.
50
+ *
51
+ * The rule for adding an entry: it must be a channel the FRAMEWORK owns, that no application route
52
+ * can occupy, and that fires as a consequence of running in dev rather than of anything the user
53
+ * did. Widening one of these until it can swallow an app endpoint converts this false negative into
54
+ * a false GREEN, so each pattern is anchored to a reserved prefix or a build-tool file suffix:
55
+ *
56
+ * - `/__nextjs` — every Next dev-overlay endpoint shares this reserved prefix (`_original-stack-frames`,
57
+ * `_original-stack-frame`, `_launch-editor`, `_source-map`, `_error_feedback`, `_server_status`,
58
+ * `_devtools_config`, `_font`, …). Verified against next@15 and next@16 `dist`.
59
+ * - `/_next/webpack-hmr` + `/_next/static/webpack/` — Next's HMR channel and the `.hot-update.*`
60
+ * chunks it fetches. `/_next/static/chunks/` and `/_next/image` are NOT here: those are the app.
61
+ * - `.hot-update.` — the webpack HMR file suffix, for any webpack app (CRA, Rspack, plain webpack).
62
+ * - `/@vite/` (`client`, `env`), `/@react-refresh`, `/__vite_ping` — the Vite dev client, which is
63
+ * what SvelteKit, Astro, Remix and plain Vite all run. Verified present in vite@7/vite@8 and in
64
+ * astro@7's dist. Vite's `/@id/` and `/@fs/` are NOT here: those load the app's own modules.
65
+ */
66
+ export declare const DevToolingChannel: {
67
+ readonly NEXT_DEV_OVERLAY: "/__nextjs";
68
+ readonly NEXT_HMR: "/_next/webpack-hmr";
69
+ readonly NEXT_HMR_CHUNKS: "/_next/static/webpack/";
70
+ readonly WEBPACK_HOT_UPDATE: ".hot-update.";
71
+ readonly VITE_CLIENT: "/@vite/";
72
+ readonly VITE_REACT_REFRESH: "/@react-refresh";
73
+ readonly VITE_PING: "/__vite_ping";
74
+ };
75
+ export type DevToolingChannel = (typeof DevToolingChannel)[keyof typeof DevToolingChannel];
76
+ /**
77
+ * Is this URL dev tooling rather than the app? Used to keep such calls out of the settle decision and
78
+ * out of contradiction hunting. Never used to HIDE the call: the event stays in the timeline and the
79
+ * exclusion is disclosed alongside the verdict.
80
+ */
81
+ export declare function isDevToolingUrl(url: string | undefined): boolean;
package/dist/net.js CHANGED
@@ -38,3 +38,47 @@ export const IpcStatus = {
38
38
  * settled, and the server reverted the shipment 1.2s later.
39
39
  */
40
40
  export const HTTP_ACCEPTED = 202;
41
+ /**
42
+ * Traffic the DEV TOOLCHAIN makes about itself — never the app under test.
43
+ *
44
+ * A CLOSED list, deliberately. Reported from a real drive: a correct Next.js navigation graded
45
+ * `verified: "no"` because the dev overlay was fetching a source map for an unrelated React key
46
+ * warning (`POST /__nextjs_original-stack-frames`), and that in-flight request counted as "the UI
47
+ * advanced over a request that never settled". Every app that logs one dev warning got a false
48
+ * negative on every action — the worst defect class after a false green.
49
+ *
50
+ * The rule for adding an entry: it must be a channel the FRAMEWORK owns, that no application route
51
+ * can occupy, and that fires as a consequence of running in dev rather than of anything the user
52
+ * did. Widening one of these until it can swallow an app endpoint converts this false negative into
53
+ * a false GREEN, so each pattern is anchored to a reserved prefix or a build-tool file suffix:
54
+ *
55
+ * - `/__nextjs` — every Next dev-overlay endpoint shares this reserved prefix (`_original-stack-frames`,
56
+ * `_original-stack-frame`, `_launch-editor`, `_source-map`, `_error_feedback`, `_server_status`,
57
+ * `_devtools_config`, `_font`, …). Verified against next@15 and next@16 `dist`.
58
+ * - `/_next/webpack-hmr` + `/_next/static/webpack/` — Next's HMR channel and the `.hot-update.*`
59
+ * chunks it fetches. `/_next/static/chunks/` and `/_next/image` are NOT here: those are the app.
60
+ * - `.hot-update.` — the webpack HMR file suffix, for any webpack app (CRA, Rspack, plain webpack).
61
+ * - `/@vite/` (`client`, `env`), `/@react-refresh`, `/__vite_ping` — the Vite dev client, which is
62
+ * what SvelteKit, Astro, Remix and plain Vite all run. Verified present in vite@7/vite@8 and in
63
+ * astro@7's dist. Vite's `/@id/` and `/@fs/` are NOT here: those load the app's own modules.
64
+ */
65
+ export const DevToolingChannel = {
66
+ NEXT_DEV_OVERLAY: '/__nextjs',
67
+ NEXT_HMR: '/_next/webpack-hmr',
68
+ NEXT_HMR_CHUNKS: '/_next/static/webpack/',
69
+ WEBPACK_HOT_UPDATE: '.hot-update.',
70
+ VITE_CLIENT: '/@vite/',
71
+ VITE_REACT_REFRESH: '/@react-refresh',
72
+ VITE_PING: '/__vite_ping',
73
+ };
74
+ const DEV_TOOLING_PATTERNS = Object.values(DevToolingChannel);
75
+ /**
76
+ * Is this URL dev tooling rather than the app? Used to keep such calls out of the settle decision and
77
+ * out of contradiction hunting. Never used to HIDE the call: the event stays in the timeline and the
78
+ * exclusion is disclosed alongside the verdict.
79
+ */
80
+ export function isDevToolingUrl(url) {
81
+ if (url === undefined)
82
+ return false;
83
+ return DEV_TOOLING_PATTERNS.some((pattern) => url.includes(pattern));
84
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * How a project's stable identity is SPELLED. The rule, once, for everyone who has to produce it.
3
+ *
4
+ * projectId is what scopes a session to an app, so the build plugin's stamp and what `reticle init`
5
+ * records into `.reticle.json` have to agree exactly or the app's sessions land under a project
6
+ * nobody is looking at. It was maintained as two byte-identical copies — `slugifyPackageName`,
7
+ * `shortHash` and `deriveProjectId` in both `@reticlehq/vite-plugin` and `@reticlehq/server` — held
8
+ * in sync by a comment asking the next contributor to keep them identical. They still were, but
9
+ * nothing would have failed on the day they were not: no test compares them, and the symptom of a
10
+ * mismatch is a session quietly filed under the wrong id.
11
+ *
12
+ * The hashing stays with the callers because it needs `node:crypto`, and core is isomorphic — the
13
+ * same split `discoverDaemonPort` already uses, where core owns the selection rule and each package
14
+ * owns its own filesystem plumbing.
15
+ */
16
+ /** How much of the digest goes into the id. Short enough to read, long enough not to collide. */
17
+ export declare const PROJECT_ID_HASH_LENGTH = 8;
18
+ /** `@acme/web` → `acme-web`; non-alphanumerics collapse to single dashes; edges trimmed. */
19
+ export declare function slugifyPackageName(name: string): string;
20
+ /**
21
+ * The stable projectId: a slug of the package name (falling back to the root's folder name, then
22
+ * `app`), plus a short fingerprint of the absolute root so two checkouts of the same package are
23
+ * still distinct.
24
+ *
25
+ * `hash` is injected rather than imported — it is the one impure, Node-only part, and passing it in
26
+ * is what lets this rule live in the isomorphic package with the callers that own `node:crypto`.
27
+ */
28
+ export declare function projectIdFrom(pkgName: string | undefined, rootPath: string, hash: (input: string) => string): string;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * How a project's stable identity is SPELLED. The rule, once, for everyone who has to produce it.
3
+ *
4
+ * projectId is what scopes a session to an app, so the build plugin's stamp and what `reticle init`
5
+ * records into `.reticle.json` have to agree exactly or the app's sessions land under a project
6
+ * nobody is looking at. It was maintained as two byte-identical copies — `slugifyPackageName`,
7
+ * `shortHash` and `deriveProjectId` in both `@reticlehq/vite-plugin` and `@reticlehq/server` — held
8
+ * in sync by a comment asking the next contributor to keep them identical. They still were, but
9
+ * nothing would have failed on the day they were not: no test compares them, and the symptom of a
10
+ * mismatch is a session quietly filed under the wrong id.
11
+ *
12
+ * The hashing stays with the callers because it needs `node:crypto`, and core is isomorphic — the
13
+ * same split `discoverDaemonPort` already uses, where core owns the selection rule and each package
14
+ * owns its own filesystem plumbing.
15
+ */
16
+ /** How much of the digest goes into the id. Short enough to read, long enough not to collide. */
17
+ export const PROJECT_ID_HASH_LENGTH = 8;
18
+ /** Fallback id base when neither the package name nor the folder name yields anything usable. */
19
+ const FALLBACK_PROJECT_BASE = 'app';
20
+ /** `@acme/web` → `acme-web`; non-alphanumerics collapse to single dashes; edges trimmed. */
21
+ export function slugifyPackageName(name) {
22
+ return name
23
+ .toLowerCase()
24
+ .replace(/^@/, '')
25
+ .replace(/[^a-z0-9]+/g, '-')
26
+ .replace(/^-+|-+$/g, '');
27
+ }
28
+ /**
29
+ * The last segment of a path — `node:path`'s `basename`, reimplemented because core may not import
30
+ * Node. Handles both separators so a Windows root produces the same id as a POSIX one.
31
+ */
32
+ function pathTail(path) {
33
+ const trimmed = path.replace(/[/\\]+$/, '');
34
+ const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
35
+ return -1 === cut ? trimmed : trimmed.slice(cut + 1);
36
+ }
37
+ /**
38
+ * The stable projectId: a slug of the package name (falling back to the root's folder name, then
39
+ * `app`), plus a short fingerprint of the absolute root so two checkouts of the same package are
40
+ * still distinct.
41
+ *
42
+ * `hash` is injected rather than imported — it is the one impure, Node-only part, and passing it in
43
+ * is what lets this rule live in the isomorphic package with the callers that own `node:crypto`.
44
+ */
45
+ export function projectIdFrom(pkgName, rootPath, hash) {
46
+ const fromName = pkgName !== undefined ? slugifyPackageName(pkgName) : '';
47
+ const base = fromName.length > 0
48
+ ? fromName
49
+ : slugifyPackageName(pathTail(rootPath)) || FALLBACK_PROJECT_BASE;
50
+ return `${base}-${hash(rootPath)}`;
51
+ }
package/dist/redaction.js CHANGED
@@ -44,7 +44,7 @@ function normalizeNames(values) {
44
44
  * key of every event, so a per-key warning would flood the console of the app it is trying to help.
45
45
  */
46
46
  export function buildRedactionPolicy(config, onWarn) {
47
- const literalKeys = normalizeNames(config?.keys?.filter((k) => typeof k === 'string'));
47
+ const literalKeys = normalizeNames(config?.keys?.filter((k) => 'string' === typeof k));
48
48
  const patterns = (config?.keys ?? []).filter((k) => k instanceof RegExp);
49
49
  const allowed = normalizeNames(config?.allow);
50
50
  // Exempting a key the default rule calls a credential is a deliberate choice with a real blast
@@ -55,8 +55,8 @@ export function buildRedactionPolicy(config, onWarn) {
55
55
  const exemptedCredentials = [...allowed].filter((key) => defaultIsSensitiveKey(key) && !literalKeys.has(key));
56
56
  if (exemptedCredentials.length > 0 && onWarn !== undefined) {
57
57
  onWarn(`[reticle] redact.allow is exempting ${exemptedCredentials.join(', ')} from redaction. The ` +
58
- `default rule treats ${exemptedCredentials.length === 1 ? 'that key' : 'those keys'} as a ` +
59
- `credential, so ${exemptedCredentials.length === 1 ? 'its value' : 'their values'} will now ` +
58
+ `default rule treats ${1 === exemptedCredentials.length ? 'that key' : 'those keys'} as a ` +
59
+ `credential, so ${1 === exemptedCredentials.length ? 'its value' : 'their values'} will now ` +
60
60
  `reach the agent transcript and the on-disk journal in cleartext.`);
61
61
  }
62
62
  return {
@@ -126,7 +126,7 @@ export function wireRedactionKeys(config) {
126
126
  if (typeof key !== 'string')
127
127
  continue;
128
128
  const trimmed = key.trim();
129
- if (trimmed.length === 0 || trimmed.length > MAX_WIRE_REDACT_KEY_LENGTH)
129
+ if (0 === trimmed.length || trimmed.length > MAX_WIRE_REDACT_KEY_LENGTH)
130
130
  continue;
131
131
  const normalized = trimmed.toLowerCase();
132
132
  if (seen.has(normalized))
@@ -43,6 +43,14 @@
43
43
  "hasCapabilities": {
44
44
  "type": "boolean"
45
45
  },
46
+ "sdkVersion": {
47
+ "type": "string",
48
+ "maxLength": 128
49
+ },
50
+ "contract": {
51
+ "type": "string",
52
+ "maxLength": 128
53
+ },
46
54
  "redactKeys": {
47
55
  "type": "array",
48
56
  "items": {
@@ -45,6 +45,14 @@
45
45
  "hasCapabilities": {
46
46
  "type": "boolean"
47
47
  },
48
+ "sdkVersion": {
49
+ "type": "string",
50
+ "maxLength": 128
51
+ },
52
+ "contract": {
53
+ "type": "string",
54
+ "maxLength": 128
55
+ },
48
56
  "redactKeys": {
49
57
  "type": "array",
50
58
  "items": {
package/dist/security.js CHANGED
@@ -1,18 +1,23 @@
1
1
  const DANGEROUS_ACTION = /\b(delete|remove|destroy|erase|drop|terminate|revoke|reset|logout|log out|sign out|close account|cancel subscription|purchase|buy|pay|place order|confirm order|deploy|publish|send|transfer|withdraw|refund)\b/i;
2
+ /** The hostnames that ARE loopback outright, with no parsing: the name, and IPv6 ::1 both ways. */
3
+ const LOOPBACK_HOSTNAMES = ['localhost', '::1', '0:0:0:0:0:0:0:1'];
4
+ /** IPv4 loopback is the whole 127.0.0.0/8 block, so the first octet is the entire test. */
5
+ const IPV4_LOOPBACK_FIRST_OCTET = '127';
6
+ const IPV4_OCTET_COUNT = 4;
7
+ const IPV4_OCTET_MAX = 255;
2
8
  /** True only for literal loopback hosts, never lookalike DNS names such as 127.example.com. */
3
9
  export function isLoopbackHostname(hostname) {
4
10
  const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
5
- if (normalized === 'localhost' || normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
11
+ if (LOOPBACK_HOSTNAMES.includes(normalized))
6
12
  return true;
7
- }
8
13
  const octets = normalized.split('.');
9
- return (octets.length === 4 &&
10
- octets[0] === '127' &&
14
+ return (IPV4_OCTET_COUNT === octets.length &&
15
+ IPV4_LOOPBACK_FIRST_OCTET === octets[0] &&
11
16
  octets.every((octet) => {
12
17
  if (!/^\d{1,3}$/.test(octet))
13
18
  return false;
14
19
  const value = Number(octet);
15
- return value >= 0 && value <= 255;
20
+ return value >= 0 && value <= IPV4_OCTET_MAX;
16
21
  }));
17
22
  }
18
23
  /**
@@ -24,3 +24,9 @@ export declare const DATA_RETICLE_SOURCE_ATTR = "data-reticle-source";
24
24
  * the build plugins, which are the only place that knows the root.
25
25
  */
26
26
  export declare const RETICLE_ROOT_GLOBAL = "__RETICLE_ROOT__";
27
+ /**
28
+ * Compile-time global carrying the SDK's own package version, so a version-skewed pair can name
29
+ * itself. Defined by the build plugins, which are the only place that can read the installed
30
+ * package's version. See `sdkVersion` on the HELLO message.
31
+ */
32
+ export declare const RETICLE_SDK_VERSION_GLOBAL = "__RETICLE_SDK_VERSION__";
@@ -24,3 +24,9 @@ export const DATA_RETICLE_SOURCE_ATTR = 'data-reticle-source';
24
24
  * the build plugins, which are the only place that knows the root.
25
25
  */
26
26
  export const RETICLE_ROOT_GLOBAL = '__RETICLE_ROOT__';
27
+ /**
28
+ * Compile-time global carrying the SDK's own package version, so a version-skewed pair can name
29
+ * itself. Defined by the build plugins, which are the only place that can read the installed
30
+ * package's version. See `sdkVersion` on the HELLO message.
31
+ */
32
+ export const RETICLE_SDK_VERSION_GLOBAL = '__RETICLE_SDK_VERSION__';
@@ -1,9 +1,10 @@
1
1
  /**
2
- * reticle_state path selection + depth capping — pure, shared by the browser SDK (which applies them
2
+ * reticle_state output projection — pure, shared by the browser SDK (which applies them
3
3
  * BEFORE the transport so a scoped read of a huge store isn't truncated) and the server (back-compat
4
4
  * fallback when an older browser returns the whole store). `selectPath` walks a dot-path (with numeric
5
5
  * array indices) and, on a miss, returns the keys that WERE available at the last good level so a wrong
6
6
  * path is diagnosable rather than a bare null. `capDepth` prunes deeply-nested values to a budget.
7
+ * `projectComponentState` strips React fiber plumbing (effect chains) from a component hook read.
7
8
  */
8
9
  /** Result of walking a dot-path: the value, or a near-miss with the keys available where it stopped. */
9
10
  export interface PathSelection {
@@ -22,7 +23,10 @@ export interface PathSelection {
22
23
  */
23
24
  totalKeys?: number;
24
25
  }
25
- /** Walk `path` (e.g. "captionCache.v3.0.text") into `root`. Empty path returns root unchanged. */
26
+ /**
27
+ * Walk `path` (e.g. "captionCache.v3.0.text") into `root`. Empty path returns root unchanged.
28
+ * Segments are own keys, canonical array indices, Map keys, or `length` on an array/string.
29
+ */
26
30
  export declare function selectPath(root: unknown, path: string): PathSelection;
27
31
  /**
28
32
  * Prune `value` to `maxDepth` levels: objects/arrays deeper than the budget collapse to a compact
@@ -30,3 +34,11 @@ export declare function selectPath(root: unknown, path: string): PathSelection;
30
34
  * budget means "no cap".
31
35
  */
32
36
  export declare function capDepth(value: unknown, maxDepth: number): unknown;
37
+ /**
38
+ * Project a component-state read down to what an agent can act on: the hook VALUES. Effect entries
39
+ * are dropped (see `EFFECT_HOOK_KEYS`); everything else — useState values, useRef, and the
40
+ * `[value, deps]` tuple of useMemo/useCallback — is passed through untouched, because React exposes
41
+ * no hook KINDS here and a two-element state value is indistinguishable from a memo tuple.
42
+ * A non-conforming value (no `hooks` array) is returned unchanged.
43
+ */
44
+ export declare function projectComponentState(result: unknown): unknown;
@@ -1,32 +1,46 @@
1
1
  /**
2
- * reticle_state path selection + depth capping — pure, shared by the browser SDK (which applies them
2
+ * reticle_state output projection — pure, shared by the browser SDK (which applies them
3
3
  * BEFORE the transport so a scoped read of a huge store isn't truncated) and the server (back-compat
4
4
  * fallback when an older browser returns the whole store). `selectPath` walks a dot-path (with numeric
5
5
  * array indices) and, on a miss, returns the keys that WERE available at the last good level so a wrong
6
6
  * path is diagnosable rather than a bare null. `capDepth` prunes deeply-nested values to a budget.
7
+ * `projectComponentState` strips React fiber plumbing (effect chains) from a component hook read.
7
8
  */
8
9
  /** Cap on how many near-miss keys travel in a failed selection — a 10k-key store must not return a
9
10
  * 10k-entry array in the error payload (that was the token blowup the near-miss exists to avoid). */
10
11
  const MAX_AVAILABLE_KEYS = 50;
12
+ /**
13
+ * The ONLY intrinsic (non-own) property a path segment may select, and only on an array or a string.
14
+ * `todos.length` is the tool's own shipped example, so it has to resolve — but a path walks UNTRUSTED
15
+ * app state, so this stays a closed one-name set rather than a general property read: anything wider
16
+ * puts `constructor`/`__proto__`/`toString` (and every array method) back on the path grammar.
17
+ */
18
+ const LENGTH_SEGMENT = 'length';
19
+ /** True where `LENGTH_SEGMENT` is a real, meaningful count — arrays and strings, nothing else. */
20
+ function hasIntrinsicLength(value) {
21
+ return Array.isArray(value) || 'string' === typeof value;
22
+ }
11
23
  /** The keys at a level, as a bounded sample plus the true count when the sample is short. */
12
24
  function keysOf(value) {
13
25
  if (Array.isArray(value)) {
14
- return {
15
- keys: value.slice(0, MAX_AVAILABLE_KEYS).map((_, i) => String(i)),
16
- total: value.length,
17
- };
26
+ // `length` is listed because it IS selectable here — answering `["First task"]` with just `["0"]`
27
+ // sent someone who mistyped `length` looking for a key that does not exist.
28
+ const indices = value.slice(0, MAX_AVAILABLE_KEYS - 1).map((_, i) => String(i));
29
+ return { keys: [...indices, LENGTH_SEGMENT], total: value.length + 1 };
18
30
  }
31
+ if ('string' === typeof value)
32
+ return { keys: [LENGTH_SEGMENT], total: 1 };
19
33
  if (value instanceof Map) {
20
34
  const keys = [];
21
35
  let total = 0;
22
36
  for (const k of value.keys()) {
23
37
  total += 1;
24
- if (typeof k === 'string' && keys.length < MAX_AVAILABLE_KEYS)
38
+ if ('string' === typeof k && keys.length < MAX_AVAILABLE_KEYS)
25
39
  keys.push(k);
26
40
  }
27
41
  return { keys, total };
28
42
  }
29
- if (typeof value === 'object' && value !== null) {
43
+ if ('object' === typeof value && value !== null) {
30
44
  const all = Object.keys(value);
31
45
  return { keys: all.slice(0, MAX_AVAILABLE_KEYS), total: all.length };
32
46
  }
@@ -42,11 +56,18 @@ function miss(value) {
42
56
  ...(total > keys.length ? { totalKeys: total } : {}),
43
57
  };
44
58
  }
45
- /** Walk `path` (e.g. "captionCache.v3.0.text") into `root`. Empty path returns root unchanged. */
59
+ /**
60
+ * Walk `path` (e.g. "captionCache.v3.0.text") into `root`. Empty path returns root unchanged.
61
+ * Segments are own keys, canonical array indices, Map keys, or `length` on an array/string.
62
+ */
46
63
  export function selectPath(root, path) {
47
64
  const segments = path.split('.').filter((s) => s.length > 0);
48
65
  let current = root;
49
66
  for (const segment of segments) {
67
+ if (LENGTH_SEGMENT === segment && hasIntrinsicLength(current)) {
68
+ current = current.length;
69
+ continue;
70
+ }
50
71
  if (Array.isArray(current)) {
51
72
  // Require a CANONICAL index string. `Number('01')`/`Number('1e0')`/`Number(' 1')` all coerce to 1,
52
73
  // so `items.01` silently read index 1 — an assertion on a path that doesn't exist quietly passed.
@@ -72,7 +93,7 @@ export function selectPath(root, path) {
72
93
  // `__proto__`, or `toString` reported found:true and returned a function from Object.prototype —
73
94
  // a state assertion on a typo'd path silently passed against a builtin instead of failing with
74
95
  // availableKeys. Only an OWN key is a real state path.
75
- if (typeof current === 'object' && current !== null && Object.hasOwn(current, segment)) {
96
+ if ('object' === typeof current && current !== null && Object.hasOwn(current, segment)) {
76
97
  current = current[segment];
77
98
  continue;
78
99
  }
@@ -91,12 +112,12 @@ export function capDepth(value, maxDepth) {
91
112
  if (value instanceof Date)
92
113
  return Number.isNaN(value.getTime()) ? null : value.toISOString();
93
114
  if (value instanceof Set) {
94
- if (maxDepth === 0)
115
+ if (0 === maxDepth)
95
116
  return `[Set(${String(value.size)})]`;
96
117
  return [...value].map((v) => capDepth(v, maxDepth - 1));
97
118
  }
98
119
  if (value instanceof Map) {
99
- if (maxDepth === 0)
120
+ if (0 === maxDepth)
100
121
  return `{Map(${String(value.size)})}`;
101
122
  const out = Object.create(null);
102
123
  for (const [k, v] of value)
@@ -104,13 +125,13 @@ export function capDepth(value, maxDepth) {
104
125
  return out;
105
126
  }
106
127
  if (Array.isArray(value)) {
107
- if (maxDepth === 0)
128
+ if (0 === maxDepth)
108
129
  return `[Array(${String(value.length)})]`;
109
130
  return value.map((v) => capDepth(v, maxDepth - 1));
110
131
  }
111
- if (typeof value === 'object' && value !== null) {
132
+ if ('object' === typeof value && value !== null) {
112
133
  const keys = Object.keys(value);
113
- if (maxDepth === 0)
134
+ if (0 === maxDepth)
114
135
  return `{…${String(keys.length)} keys}`;
115
136
  // Null-proto target: a wire object can carry an own `__proto__` key (via JSON.parse), and
116
137
  // `out['__proto__'] = …` on a normal object writes the prototype slot instead of a key, losing
@@ -122,3 +143,45 @@ export function capDepth(value, maxDepth) {
122
143
  }
123
144
  return value;
124
145
  }
146
+ /**
147
+ * Keys a React effect hook's `memoizedState` can carry once sanitized: `create`/`destroy` are
148
+ * functions (already nulled), `deps` re-states values the value-hooks above it already carry, and
149
+ * `next` chains the WHOLE effect list into every effect entry — so N effects cost O(N^2) of nulls.
150
+ * React 18 uses `destroy`, React 19 wraps it in `inst`; both are listed so either version matches.
151
+ */
152
+ const EFFECT_HOOK_KEYS = new Set(['tag', 'create', 'destroy', 'deps', 'inst', 'next']);
153
+ /** Disclosure text for a projected hook list — a trim is never silent. */
154
+ const HOOKS_PROJECTED_NOTE = 'projected — effect hook(s) dropped (create/destroy are functions, deps duplicate the state values, and each entry re-chains the whole effect list). Every state/memo/ref hook value is unchanged.';
155
+ /** True for a sanitized React effect object — internals with no value an agent can act on. */
156
+ function isEffectHook(value) {
157
+ if ('object' !== typeof value || null === value || Array.isArray(value))
158
+ return false;
159
+ const keys = Object.keys(value);
160
+ if (!keys.includes('tag') || !keys.includes('deps') || !keys.includes('next'))
161
+ return false;
162
+ if ('number' !== typeof value.tag)
163
+ return false;
164
+ return keys.every((k) => EFFECT_HOOK_KEYS.has(k));
165
+ }
166
+ /**
167
+ * Project a component-state read down to what an agent can act on: the hook VALUES. Effect entries
168
+ * are dropped (see `EFFECT_HOOK_KEYS`); everything else — useState values, useRef, and the
169
+ * `[value, deps]` tuple of useMemo/useCallback — is passed through untouched, because React exposes
170
+ * no hook KINDS here and a two-element state value is indistinguishable from a memo tuple.
171
+ * A non-conforming value (no `hooks` array) is returned unchanged.
172
+ */
173
+ export function projectComponentState(result) {
174
+ if ('object' !== typeof result || null === result)
175
+ return result;
176
+ const hooks = result.hooks;
177
+ if (!Array.isArray(hooks))
178
+ return result;
179
+ const kept = hooks.filter((h) => !isEffectHook(h));
180
+ if (kept.length === hooks.length)
181
+ return result;
182
+ return {
183
+ ...result,
184
+ hooks: kept,
185
+ truncation: { droppedItems: hooks.length - kept.length, note: HOOKS_PROJECTED_NOTE },
186
+ };
187
+ }