@copilotkit/shared 1.79.2-canary.1792172552 → 1.81.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 (156) hide show
  1. package/dist/a2ui-envelope.cjs +154 -0
  2. package/dist/a2ui-envelope.cjs.map +1 -0
  3. package/dist/a2ui-envelope.d.cts +101 -0
  4. package/dist/a2ui-envelope.d.cts.map +1 -0
  5. package/dist/a2ui-envelope.d.mts +101 -0
  6. package/dist/a2ui-envelope.d.mts.map +1 -0
  7. package/dist/a2ui-envelope.mjs +151 -0
  8. package/dist/a2ui-envelope.mjs.map +1 -0
  9. package/dist/a2ui-prompts.cjs +139 -0
  10. package/dist/a2ui-prompts.cjs.map +1 -1
  11. package/dist/a2ui-prompts.d.cts +60 -1
  12. package/dist/a2ui-prompts.d.cts.map +1 -1
  13. package/dist/a2ui-prompts.d.mts +60 -1
  14. package/dist/a2ui-prompts.d.mts.map +1 -1
  15. package/dist/a2ui-prompts.mjs +134 -1
  16. package/dist/a2ui-prompts.mjs.map +1 -1
  17. package/dist/constants/index.cjs +7 -0
  18. package/dist/constants/index.cjs.map +1 -1
  19. package/dist/constants/index.d.cts +7 -1
  20. package/dist/constants/index.d.cts.map +1 -1
  21. package/dist/constants/index.d.mts +7 -1
  22. package/dist/constants/index.d.mts.map +1 -1
  23. package/dist/constants/index.mjs +7 -1
  24. package/dist/constants/index.mjs.map +1 -1
  25. package/dist/event-transforms/open-generative-ui-middleware.cjs +7 -6
  26. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +1 -1
  27. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +1 -1
  28. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +1 -1
  29. package/dist/event-transforms/open-generative-ui-middleware.mjs +7 -6
  30. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +1 -1
  31. package/dist/generative-ui/basic-functions.cjs +177 -0
  32. package/dist/generative-ui/basic-functions.cjs.map +1 -0
  33. package/dist/generative-ui/basic-functions.d.cts +108 -0
  34. package/dist/generative-ui/basic-functions.d.cts.map +1 -0
  35. package/dist/generative-ui/basic-functions.d.mts +108 -0
  36. package/dist/generative-ui/basic-functions.d.mts.map +1 -0
  37. package/dist/generative-ui/basic-functions.mjs +167 -0
  38. package/dist/generative-ui/basic-functions.mjs.map +1 -0
  39. package/dist/generative-ui/child-refs.cjs +161 -0
  40. package/dist/generative-ui/child-refs.cjs.map +1 -0
  41. package/dist/generative-ui/child-refs.d.cts +68 -0
  42. package/dist/generative-ui/child-refs.d.cts.map +1 -0
  43. package/dist/generative-ui/child-refs.d.mts +68 -0
  44. package/dist/generative-ui/child-refs.d.mts.map +1 -0
  45. package/dist/generative-ui/child-refs.mjs +152 -0
  46. package/dist/generative-ui/child-refs.mjs.map +1 -0
  47. package/dist/generative-ui/is-record.cjs +10 -0
  48. package/dist/generative-ui/is-record.cjs.map +1 -0
  49. package/dist/generative-ui/is-record.mjs +9 -0
  50. package/dist/generative-ui/is-record.mjs.map +1 -0
  51. package/dist/generative-ui/prompt.cjs +91 -0
  52. package/dist/generative-ui/prompt.cjs.map +1 -0
  53. package/dist/generative-ui/prompt.d.cts +13 -0
  54. package/dist/generative-ui/prompt.d.cts.map +1 -0
  55. package/dist/generative-ui/prompt.d.mts +13 -0
  56. package/dist/generative-ui/prompt.d.mts.map +1 -0
  57. package/dist/generative-ui/prompt.mjs +90 -0
  58. package/dist/generative-ui/prompt.mjs.map +1 -0
  59. package/dist/generative-ui/render-ui-args.cjs +160 -0
  60. package/dist/generative-ui/render-ui-args.cjs.map +1 -0
  61. package/dist/generative-ui/render-ui-args.d.cts +40 -0
  62. package/dist/generative-ui/render-ui-args.d.cts.map +1 -0
  63. package/dist/generative-ui/render-ui-args.d.mts +40 -0
  64. package/dist/generative-ui/render-ui-args.d.mts.map +1 -0
  65. package/dist/generative-ui/render-ui-args.mjs +159 -0
  66. package/dist/generative-ui/render-ui-args.mjs.map +1 -0
  67. package/dist/generative-ui/types.cjs +101 -0
  68. package/dist/generative-ui/types.cjs.map +1 -0
  69. package/dist/generative-ui/types.d.cts +270 -0
  70. package/dist/generative-ui/types.d.cts.map +1 -0
  71. package/dist/generative-ui/types.d.mts +270 -0
  72. package/dist/generative-ui/types.d.mts.map +1 -0
  73. package/dist/generative-ui/types.mjs +86 -0
  74. package/dist/generative-ui/types.mjs.map +1 -0
  75. package/dist/generative-ui/validate-operation.cjs +405 -0
  76. package/dist/generative-ui/validate-operation.cjs.map +1 -0
  77. package/dist/generative-ui/validate-operation.d.cts +86 -0
  78. package/dist/generative-ui/validate-operation.d.cts.map +1 -0
  79. package/dist/generative-ui/validate-operation.d.mts +86 -0
  80. package/dist/generative-ui/validate-operation.d.mts.map +1 -0
  81. package/dist/generative-ui/validate-operation.mjs +399 -0
  82. package/dist/generative-ui/validate-operation.mjs.map +1 -0
  83. package/dist/index.cjs +64 -0
  84. package/dist/index.cjs.map +1 -1
  85. package/dist/index.d.cts +11 -4
  86. package/dist/index.d.cts.map +1 -1
  87. package/dist/index.d.mts +11 -4
  88. package/dist/index.d.mts.map +1 -1
  89. package/dist/index.mjs +10 -3
  90. package/dist/index.mjs.map +1 -1
  91. package/dist/index.umd.js +1466 -29
  92. package/dist/index.umd.js.map +1 -1
  93. package/dist/package.cjs +1 -1
  94. package/dist/package.mjs +1 -1
  95. package/dist/telemetry/lambda-client.cjs.map +1 -1
  96. package/dist/telemetry/lambda-client.mjs.map +1 -1
  97. package/dist/telemetry/utils.cjs +0 -2
  98. package/dist/telemetry/utils.cjs.map +1 -1
  99. package/dist/telemetry/utils.mjs +0 -2
  100. package/dist/telemetry/utils.mjs.map +1 -1
  101. package/dist/utils/dashboard-url.cjs +19 -0
  102. package/dist/utils/dashboard-url.cjs.map +1 -0
  103. package/dist/utils/dashboard-url.mjs +18 -0
  104. package/dist/utils/dashboard-url.mjs.map +1 -0
  105. package/dist/utils/index.cjs +2 -1
  106. package/dist/utils/index.cjs.map +1 -1
  107. package/dist/utils/index.d.cts +1 -1
  108. package/dist/utils/index.d.cts.map +1 -1
  109. package/dist/utils/index.d.mts +1 -1
  110. package/dist/utils/index.d.mts.map +1 -1
  111. package/dist/utils/index.mjs +2 -1
  112. package/dist/utils/index.mjs.map +1 -1
  113. package/dist/utils/inspector-learning.cjs +48 -16
  114. package/dist/utils/inspector-learning.cjs.map +1 -1
  115. package/dist/utils/inspector-learning.d.cts +14 -1
  116. package/dist/utils/inspector-learning.d.cts.map +1 -1
  117. package/dist/utils/inspector-learning.d.mts +14 -1
  118. package/dist/utils/inspector-learning.d.mts.map +1 -1
  119. package/dist/utils/inspector-learning.mjs +49 -16
  120. package/dist/utils/inspector-learning.mjs.map +1 -1
  121. package/dist/utils/inspector-metadata.cjs +2 -3
  122. package/dist/utils/inspector-metadata.cjs.map +1 -1
  123. package/dist/utils/inspector-metadata.d.cts.map +1 -1
  124. package/dist/utils/inspector-metadata.d.mts.map +1 -1
  125. package/dist/utils/inspector-metadata.mjs +3 -3
  126. package/dist/utils/inspector-metadata.mjs.map +1 -1
  127. package/package.json +3 -4
  128. package/src/__tests__/a2ui-envelope.test.ts +434 -0
  129. package/src/__tests__/a2ui-prompts.test.ts +362 -0
  130. package/src/a2ui-envelope.ts +309 -0
  131. package/src/a2ui-prompts.ts +207 -0
  132. package/src/constants/index.ts +7 -0
  133. package/src/event-transforms/open-generative-ui-middleware.ts +19 -10
  134. package/src/generative-ui/__tests__/render-ui-args.test.ts +175 -0
  135. package/src/generative-ui/__tests__/validate-operation.test.ts +977 -0
  136. package/src/generative-ui/basic-functions.ts +282 -0
  137. package/src/generative-ui/child-refs.ts +210 -0
  138. package/src/generative-ui/index.ts +6 -0
  139. package/src/generative-ui/is-record.ts +4 -0
  140. package/src/generative-ui/prompt.ts +174 -0
  141. package/src/generative-ui/render-ui-args.ts +199 -0
  142. package/src/generative-ui/types.ts +314 -0
  143. package/src/generative-ui/validate-operation.ts +723 -0
  144. package/src/index.ts +15 -0
  145. package/src/telemetry/lambda-client.ts +3 -3
  146. package/src/telemetry/utils.ts +0 -28
  147. package/src/utils/dashboard-url.ts +17 -0
  148. package/src/utils/index.ts +7 -1
  149. package/src/utils/inspector-learning.test.ts +210 -0
  150. package/src/utils/inspector-learning.ts +117 -17
  151. package/src/utils/inspector-metadata.test.ts +2 -1
  152. package/src/utils/inspector-metadata.ts +3 -13
  153. package/src/utils.test.ts +71 -0
  154. package/tsdown.config.ts +0 -1
  155. package/src/telemetry/scarf-client.ts +0 -39
  156. package/src/telemetry/security-check.ts +0 -0
package/src/index.ts CHANGED
@@ -174,8 +174,23 @@ export function createLicenseContextValue(
174
174
  export {
175
175
  A2UI_DEFAULT_GENERATION_GUIDELINES,
176
176
  A2UI_DEFAULT_DESIGN_GUIDELINES,
177
+ ALL_GENERATIVE_UI_GUIDE_FEATURES,
178
+ buildGenerativeUIMarkdownGuidelines,
179
+ generativeUIGuideFeatures,
180
+ GENERATIVE_UI_MARKDOWN_GUIDELINES,
181
+ GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
182
+ GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
177
183
  } from "./a2ui-prompts";
184
+ export type { GenerativeUIGuideFeatures } from "./a2ui-prompts";
185
+ export {
186
+ COPILOTKIT_FORWARDED_PROPS_KEY,
187
+ COPILOTKIT_UI_ENVELOPE_FORMAT,
188
+ envelopeToManifest,
189
+ readCopilotKitUIEnvelope,
190
+ } from "./a2ui-envelope";
191
+ export type { CopilotKitUIEnvelope } from "./a2ui-envelope";
178
192
 
179
193
  export type { DebugEventEnvelope } from "./debug-event-envelope";
180
194
 
181
195
  export { GENERATE_SANDBOXED_UI_DESCRIPTION } from "./open-generative-ui-prompts";
196
+ export * from "./generative-ui";
@@ -2,9 +2,9 @@
2
2
  //
3
3
  // Posts events to a CopilotKit-controlled telemetry-sink endpoint, which
4
4
  // fans out to Scarf, Reo, and any future destinations. Replaces the direct
5
- // per-vendor calls (scarf-client.ts) so that vendor changes don't require
6
- // SDK releases and so that downstream services we don't want exposed to
7
- // OSS readers (e.g. the email-enrichment service backing Reo) stay
5
+ // per-vendor calls (formerly a Scarf-specific client) so that vendor changes
6
+ // don't require SDK releases and so that downstream services we don't want
7
+ // exposed to OSS readers (e.g. the email-enrichment service backing Reo) stay
8
8
  // private.
9
9
  //
10
10
  // Two attribution modes:
@@ -1,5 +1,3 @@
1
- import chalk from "chalk";
2
-
3
1
  export function flattenObject(
4
2
  obj: Record<string, any>,
5
3
  parentKey = "",
@@ -15,29 +13,3 @@ export function flattenObject(
15
13
  }
16
14
  return res;
17
15
  }
18
-
19
- export function printSecurityNotice(advisory: {
20
- advisory: string | null;
21
- message: string;
22
- severity: "low" | "medium" | "high" | "none";
23
- }) {
24
- const severityColor =
25
- {
26
- low: chalk.blue,
27
- medium: chalk.yellow,
28
- high: chalk.red,
29
- }[advisory.severity.toLowerCase()] || chalk.white;
30
-
31
- console.log();
32
- console.log(
33
- `━━━━━━━━━━━━━━━━━━ ${chalk.bold(`CopilotKit`)} ━━━━━━━━━━━━━━━━━━`,
34
- );
35
- console.log();
36
- console.log(
37
- `${chalk.bold(`Severity: ${severityColor(advisory.severity.toUpperCase())}`)}`,
38
- );
39
- console.log();
40
- console.log(`${chalk.bold(advisory.message)}`);
41
- console.log();
42
- console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
43
- }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Checks dashboard navigation transport and credentials only.
3
+ * Callers must separately enforce the configured origin and allowed paths.
4
+ * This policy does not authorize server-side requests.
5
+ */
6
+ export function isSafeDashboardUrl(url: URL): boolean {
7
+ const local =
8
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) ||
9
+ /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+localhost$/u.test(
10
+ url.hostname,
11
+ );
12
+ return (
13
+ !url.username &&
14
+ !url.password &&
15
+ (url.protocol === "https:" || (url.protocol === "http:" && local))
16
+ );
17
+ }
@@ -27,13 +27,19 @@ export function parseJson(json: string, fallback: any = "unset") {
27
27
  }
28
28
  }
29
29
 
30
+ // Allow partial values of every type except unterminated numbers. A cut-off
31
+ // number is a *different* number (`{"max":1` is about to become 100, not 1),
32
+ // while a cut-off string is still the beginning of the final string. Numbers
33
+ // therefore only appear once terminated by `,`, `}` or `]`.
34
+ const PARTIAL_JSON_ALLOW = PartialJSON.Allow.ALL & ~PartialJSON.Allow.NUM;
35
+
30
36
  /**
31
37
  * Parses a partial/incomplete JSON string, returning as much valid data as possible.
32
38
  * Falls back to an empty object if parsing fails entirely.
33
39
  */
34
40
  export function partialJSONParse(json: string) {
35
41
  try {
36
- const parsed = PartialJSON.parse(json);
42
+ const parsed = PartialJSON.parse(json, PARTIAL_JSON_ALLOW);
37
43
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
38
44
  return parsed;
39
45
  }
@@ -35,6 +35,59 @@ const emptySnapshot = () => ({
35
35
  },
36
36
  });
37
37
 
38
+ /** One available Trajectory citation, with fields overridden per case. */
39
+ const trajectoryEntry = (overrides: Record<string, unknown>) => ({
40
+ status: "available",
41
+ trajectoryId: "trajectory-1",
42
+ eventCount: 1,
43
+ url: "https://app.copilotkit.ai/o/acme/support/trajectories/trajectory-1",
44
+ ...overrides,
45
+ });
46
+
47
+ /** Builds a configured snapshot whose Insight and Skill source cite Trajectories. */
48
+ const snapshotWithTrajectoryEvidence = (trajectoryEvidence: unknown[]) => {
49
+ const insight = {
50
+ id: "insight-1",
51
+ statement: "Users switch the theme first.",
52
+ impact: "Default to dark mode.",
53
+ totalThreadCount: 0,
54
+ evidenceTruncated: false,
55
+ evidence: [],
56
+ totalTrajectoryCount: trajectoryEvidence.length,
57
+ trajectoryEvidence,
58
+ };
59
+ return {
60
+ ...emptySnapshot(),
61
+ configuration: {
62
+ state: "configured",
63
+ container: { id: "support", name: "Support" },
64
+ },
65
+ skillsPage: {
66
+ page: 1,
67
+ pageSize: 3,
68
+ total: 1,
69
+ totalPages: 1,
70
+ items: [
71
+ {
72
+ id: "skill-1",
73
+ name: "dark-mode",
74
+ description: "Offer dark mode.",
75
+ revision: 1,
76
+ skillMd: "# Dark mode",
77
+ sourceInsight: { ...insight, id: "source-1" },
78
+ },
79
+ ],
80
+ },
81
+ insightsPage: {
82
+ page: 1,
83
+ pageSize: 4,
84
+ total: 1,
85
+ totalPages: 1,
86
+ items: [insight],
87
+ },
88
+ };
89
+ };
90
+
38
91
  describe("Inspector Learning wire validation", () => {
39
92
  it("accepts and copies a bounded V1 snapshot", () => {
40
93
  const source = emptySnapshot();
@@ -197,6 +250,105 @@ describe("Inspector Learning wire validation", () => {
197
250
  expect(parseInspectorLearningSnapshotV1(snapshot)).toBeUndefined();
198
251
  });
199
252
 
253
+ it("copies Trajectory evidence next to the Thread evidence", () => {
254
+ const snapshot = snapshotWithTrajectoryEvidence([
255
+ {
256
+ status: "available",
257
+ trajectoryId: "0190a3b4-0000-7000-8000-000000000001",
258
+ eventCount: 2,
259
+ url: "https://app.copilotkit.ai/o/acme/support/trajectories/0190a3b4-0000-7000-8000-000000000001?event=901",
260
+ },
261
+ { status: "unavailable" },
262
+ ]);
263
+
264
+ const parsed = parseInspectorLearningSnapshotV1(snapshot);
265
+
266
+ expect(parsed?.insightsPage.items[0]).toEqual(
267
+ snapshot.insightsPage.items[0],
268
+ );
269
+ expect(
270
+ parseInspectorLearningSnapshotV1(
271
+ snapshotWithTrajectoryEvidence([
272
+ {
273
+ status: "available",
274
+ trajectoryId: "trajectory-1",
275
+ eventCount: 1,
276
+ url: "https://app.copilotkit.ai/o/acme/support/trajectories/trajectory-1",
277
+ addedLater: "ignored",
278
+ },
279
+ ]),
280
+ )?.insightsPage.items[0]?.trajectoryEvidence,
281
+ ).toEqual([
282
+ {
283
+ status: "available",
284
+ trajectoryId: "trajectory-1",
285
+ eventCount: 1,
286
+ url: "https://app.copilotkit.ai/o/acme/support/trajectories/trajectory-1",
287
+ },
288
+ ]);
289
+ expect(parsed?.skillsPage.items[0]?.sourceInsight).toEqual(
290
+ snapshot.skillsPage.items[0]?.sourceInsight,
291
+ );
292
+ });
293
+
294
+ it("accepts Insights from producers that omit Trajectory evidence", () => {
295
+ const snapshot = snapshotWithTrajectoryEvidence([]);
296
+ const [insight] = snapshot.insightsPage.items;
297
+ delete (insight as { totalTrajectoryCount?: number }).totalTrajectoryCount;
298
+ delete (insight as { trajectoryEvidence?: unknown }).trajectoryEvidence;
299
+
300
+ const parsed = parseInspectorLearningSnapshotV1(snapshot);
301
+
302
+ expect(parsed?.insightsPage.items[0]).toEqual(insight);
303
+ expect(parsed?.insightsPage.items[0]).not.toHaveProperty(
304
+ "trajectoryEvidence",
305
+ );
306
+ });
307
+
308
+ it("keeps either Trajectory field when the producer sends only one", () => {
309
+ const evidence = [trajectoryEntry({}), { status: "unavailable" }];
310
+ const countOnly = snapshotWithTrajectoryEvidence(evidence);
311
+ delete (countOnly.insightsPage.items[0] as { trajectoryEvidence?: unknown })
312
+ .trajectoryEvidence;
313
+ const evidenceOnly = snapshotWithTrajectoryEvidence(evidence);
314
+ delete (
315
+ evidenceOnly.insightsPage.items[0] as { totalTrajectoryCount?: number }
316
+ ).totalTrajectoryCount;
317
+
318
+ const parsedCountOnly = parseInspectorLearningSnapshotV1(countOnly);
319
+ const parsedEvidenceOnly = parseInspectorLearningSnapshotV1(evidenceOnly);
320
+
321
+ expect(parsedCountOnly?.insightsPage.items[0]).toEqual(
322
+ countOnly.insightsPage.items[0],
323
+ );
324
+ expect(parsedEvidenceOnly?.insightsPage.items[0]).toEqual(
325
+ evidenceOnly.insightsPage.items[0],
326
+ );
327
+ });
328
+
329
+ it("rejects Trajectory evidence with foreign links or unknown fields", () => {
330
+ for (const invalid of [
331
+ trajectoryEntry({
332
+ url: "https://attacker.example/o/acme/support/trajectories/t",
333
+ }),
334
+ trajectoryEntry({ url: "javascript:alert(1)" }),
335
+ trajectoryEntry({ eventCount: -1 }),
336
+ trajectoryEntry({ trajectoryId: "" }),
337
+ { status: "unavailable", trajectoryId: "former-id" },
338
+ { status: "pending" },
339
+ ]) {
340
+ expect(
341
+ parseInspectorLearningSnapshotV1(
342
+ snapshotWithTrajectoryEvidence([invalid]),
343
+ ),
344
+ ).toBeUndefined();
345
+ }
346
+ const tooMany = snapshotWithTrajectoryEvidence(
347
+ Array.from({ length: 101 }, () => ({ status: "unavailable" })),
348
+ );
349
+ expect(parseInspectorLearningSnapshotV1(tooMany)).toBeUndefined();
350
+ });
351
+
200
352
  it("accepts only the browser-owned scope and pagination fields", () => {
201
353
  expect(
202
354
  parseInspectorLearningRequestV1({
@@ -211,3 +363,61 @@ describe("Inspector Learning wire validation", () => {
211
363
  expect(parseInspectorLearningRequestV1({ skillsPage: 0 })).toBeUndefined();
212
364
  });
213
365
  });
366
+
367
+ it.each([
368
+ "http://localhost:7066",
369
+ "http://127.0.0.1:7066",
370
+ "http://[::1]:7066",
371
+ "http://cpk.localhost:7066",
372
+ "http://team.cpk.localhost:7066",
373
+ "https://dashboard.example.com",
374
+ ])("accepts Learning links on configured dashboard origin %s", (origin) => {
375
+ const url = `${origin}/o/acme/support/learning`;
376
+
377
+ expect(parseInspectorLearningUrl(url, origin)).toBe(url);
378
+ });
379
+
380
+ it.each([
381
+ "http://remote.example.com",
382
+ "http://cpk.localhost.example.com",
383
+ "http://-bad.localhost",
384
+ "http://bad_.localhost",
385
+ "http://bad..localhost",
386
+ "http://user:password@cpk.localhost",
387
+ "ftp://cpk.localhost",
388
+ "javascript:alert(1)",
389
+ ])("rejects unsafe dashboard origin %s", (origin) => {
390
+ expect(
391
+ parseInspectorLearningUrl(`${origin}/o/acme/support/learning`, origin),
392
+ ).toBeUndefined();
393
+ });
394
+
395
+ it.each([
396
+ "http://localhost:7066",
397
+ "http://cpk.localhost:7067",
398
+ "https://cpk.localhost:7066",
399
+ "https://other.example.com",
400
+ ])("rejects a Learning link to another origin %s", (origin) => {
401
+ expect(
402
+ parseInspectorLearningUrl(
403
+ `${origin}/o/acme/support/learning`,
404
+ "http://cpk.localhost:7066",
405
+ ),
406
+ ).toBeUndefined();
407
+ });
408
+
409
+ it.each([
410
+ ["learning", "/account"],
411
+ ["learning", "/o/acme/support/learning?redirect=elsewhere"],
412
+ ["candidates", "/o/acme/support/learning/quality/analysis-results"],
413
+ ["runs", "/o/acme/support/learning/quality/skills"],
414
+ ["runs", "/o/acme/support/learning/quality/analysis-results#fragment"],
415
+ ])("rejects invalid %s Learning path %s", (field, path) => {
416
+ const snapshot = emptySnapshot();
417
+ expect(
418
+ parseInspectorLearningSnapshotV1({
419
+ ...snapshot,
420
+ links: { ...snapshot.links, [field]: `${snapshot.webAppOrigin}${path}` },
421
+ }),
422
+ ).toBeUndefined();
423
+ });
@@ -1,3 +1,5 @@
1
+ import { isSafeDashboardUrl } from "./dashboard-url";
2
+
1
3
  /** A bounded page in the Inspector Learning snapshot. */
2
4
  export interface InspectorLearningPage<T> {
3
5
  readonly page: number;
@@ -17,6 +19,16 @@ export type InspectorLearningEvidence =
17
19
  }
18
20
  | { readonly status: "unavailable" };
19
21
 
22
+ /** A cited Trajectory, linked into the Intelligence web app. */
23
+ export type InspectorLearningTrajectoryEvidence =
24
+ | {
25
+ readonly status: "available";
26
+ readonly trajectoryId: string;
27
+ readonly eventCount: number;
28
+ readonly url: string;
29
+ }
30
+ | { readonly status: "unavailable" };
31
+
20
32
  export interface InspectorLearningInsight {
21
33
  readonly id: string;
22
34
  readonly statement: string;
@@ -24,6 +36,10 @@ export interface InspectorLearningInsight {
24
36
  readonly totalThreadCount: number;
25
37
  readonly evidenceTruncated: boolean;
26
38
  readonly evidence: readonly InspectorLearningEvidence[];
39
+ /** Absent when Intelligence predates Trajectory evidence. */
40
+ readonly totalTrajectoryCount?: number;
41
+ /** Absent when Intelligence predates Trajectory evidence. */
42
+ readonly trajectoryEvidence?: readonly InspectorLearningTrajectoryEvidence[];
27
43
  }
28
44
 
29
45
  export interface InspectorLearningSkill {
@@ -118,9 +134,6 @@ export function parseInspectorLearningUrl(
118
134
  try {
119
135
  const parsed = new URL(value);
120
136
  const configured = new URL(trustedOrigin);
121
- const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(
122
- configured.hostname,
123
- );
124
137
  if (
125
138
  parsed.username ||
126
139
  parsed.password ||
@@ -129,8 +142,7 @@ export function parseInspectorLearningUrl(
129
142
  configured.pathname !== "/" ||
130
143
  configured.search ||
131
144
  configured.hash ||
132
- (configured.protocol !== "https:" &&
133
- !(configured.protocol === "http:" && loopback)) ||
145
+ !isSafeDashboardUrl(configured) ||
134
146
  parsed.origin !== configured.origin
135
147
  ) {
136
148
  return undefined;
@@ -141,6 +153,26 @@ export function parseInspectorLearningUrl(
141
153
  }
142
154
  }
143
155
 
156
+ /** Validates the canonical dashboard route after the origin check. */
157
+ function validLearningPath(
158
+ value: string,
159
+ kind: "learning" | "candidates" | "runs",
160
+ ): boolean {
161
+ const url = new URL(value);
162
+ if (url.search || url.hash) return false;
163
+ if (kind === "learning") {
164
+ return (
165
+ url.pathname === "/learning" ||
166
+ /^\/o\/[^/]+\/[^/]+\/learning(?:\/[^/]+)?$/u.test(url.pathname)
167
+ );
168
+ }
169
+ return kind === "candidates"
170
+ ? /^\/o\/[^/]+\/[^/]+\/learning\/[^/]+\/skills$/u.test(url.pathname)
171
+ : /^\/o\/[^/]+\/[^/]+\/learning\/[^/]+\/analysis-results$/u.test(
172
+ url.pathname,
173
+ );
174
+ }
175
+
144
176
  function parseEvidence(value: unknown): InspectorLearningEvidence | undefined {
145
177
  if (record(value) && value.status === "unavailable") {
146
178
  return Object.keys(value).length === 1
@@ -177,7 +209,37 @@ function parseEvidence(value: unknown): InspectorLearningEvidence | undefined {
177
209
  };
178
210
  }
179
211
 
180
- function parseInsight(value: unknown): InspectorLearningInsight | undefined {
212
+ function parseTrajectoryEvidence(
213
+ value: unknown,
214
+ webAppOrigin: string,
215
+ ): InspectorLearningTrajectoryEvidence | undefined {
216
+ if (record(value) && value.status === "unavailable") {
217
+ return Object.keys(value).length === 1
218
+ ? { status: "unavailable" }
219
+ : undefined;
220
+ }
221
+ if (
222
+ !record(value) ||
223
+ value.status !== "available" ||
224
+ !string(value.trajectoryId, 128) ||
225
+ !integer(value.eventCount)
226
+ ) {
227
+ return undefined;
228
+ }
229
+ const url = parseInspectorLearningUrl(value.url, webAppOrigin);
230
+ if (!url) return undefined;
231
+ return {
232
+ status: "available",
233
+ trajectoryId: value.trajectoryId,
234
+ eventCount: value.eventCount,
235
+ url,
236
+ };
237
+ }
238
+
239
+ function parseInsight(
240
+ value: unknown,
241
+ webAppOrigin: string,
242
+ ): InspectorLearningInsight | undefined {
181
243
  if (
182
244
  !record(value) ||
183
245
  !string(value.id, 128) ||
@@ -192,7 +254,7 @@ function parseInsight(value: unknown): InspectorLearningInsight | undefined {
192
254
  }
193
255
  const evidence = value.evidence.map(parseEvidence);
194
256
  if (evidence.some((item) => item === undefined)) return undefined;
195
- return {
257
+ const insight: InspectorLearningInsight = {
196
258
  id: value.id,
197
259
  statement: value.statement,
198
260
  impact: value.impact,
@@ -200,9 +262,38 @@ function parseInsight(value: unknown): InspectorLearningInsight | undefined {
200
262
  evidenceTruncated: value.evidenceTruncated,
201
263
  evidence: evidence as InspectorLearningEvidence[],
202
264
  };
265
+ // Each Trajectory field is optional on its own; a malformed one rejects
266
+ // the Insight, an absent one leaves the Thread-only shape untouched.
267
+ let totalTrajectoryCount: number | undefined;
268
+ if (value.totalTrajectoryCount !== undefined) {
269
+ if (!integer(value.totalTrajectoryCount)) return undefined;
270
+ totalTrajectoryCount = value.totalTrajectoryCount;
271
+ }
272
+ let trajectoryEvidence: InspectorLearningTrajectoryEvidence[] | undefined;
273
+ if (value.trajectoryEvidence !== undefined) {
274
+ if (
275
+ !Array.isArray(value.trajectoryEvidence) ||
276
+ value.trajectoryEvidence.length > 100
277
+ ) {
278
+ return undefined;
279
+ }
280
+ const parsed = value.trajectoryEvidence.map((item) =>
281
+ parseTrajectoryEvidence(item, webAppOrigin),
282
+ );
283
+ if (parsed.some((item) => item === undefined)) return undefined;
284
+ trajectoryEvidence = parsed as InspectorLearningTrajectoryEvidence[];
285
+ }
286
+ return {
287
+ ...insight,
288
+ ...(totalTrajectoryCount === undefined ? {} : { totalTrajectoryCount }),
289
+ ...(trajectoryEvidence === undefined ? {} : { trajectoryEvidence }),
290
+ };
203
291
  }
204
292
 
205
- function parseSkill(value: unknown): InspectorLearningSkill | undefined {
293
+ function parseSkill(
294
+ value: unknown,
295
+ webAppOrigin: string,
296
+ ): InspectorLearningSkill | undefined {
206
297
  if (
207
298
  !record(value) ||
208
299
  !string(value.id, 128) ||
@@ -215,7 +306,9 @@ function parseSkill(value: unknown): InspectorLearningSkill | undefined {
215
306
  return undefined;
216
307
  }
217
308
  const sourceInsight =
218
- value.sourceInsight === null ? null : parseInsight(value.sourceInsight);
309
+ value.sourceInsight === null
310
+ ? null
311
+ : parseInsight(value.sourceInsight, webAppOrigin);
219
312
  if (sourceInsight === undefined) return undefined;
220
313
  return {
221
314
  id: value.id,
@@ -329,9 +422,19 @@ export function parseInspectorLearningSnapshotV1(
329
422
  ) {
330
423
  return undefined;
331
424
  }
425
+ const originUrl = parseInspectorLearningUrl(
426
+ value.webAppOrigin,
427
+ value.webAppOrigin,
428
+ );
429
+ if (!originUrl || new URL(originUrl).pathname !== "/") return undefined;
430
+ const webAppOrigin = new URL(originUrl).origin;
332
431
  const configuration = parseConfiguration(value.configuration);
333
- const skillsPage = parsePage(value.skillsPage, 3, parseSkill);
334
- const insightsPage = parsePage(value.insightsPage, 4, parseInsight);
432
+ const skillsPage = parsePage(value.skillsPage, 3, (item) =>
433
+ parseSkill(item, webAppOrigin),
434
+ );
435
+ const insightsPage = parsePage(value.insightsPage, 4, (item) =>
436
+ parseInsight(item, webAppOrigin),
437
+ );
335
438
  if (!configuration || !skillsPage || !insightsPage) return undefined;
336
439
  let latest: InspectorLearningSnapshotV1["run"]["latest"] = null;
337
440
  if (value.run.latest !== null) {
@@ -352,12 +455,6 @@ export function parseInspectorLearningSnapshotV1(
352
455
  };
353
456
  }
354
457
  if (!record(value.links)) return undefined;
355
- const originUrl = parseInspectorLearningUrl(
356
- value.webAppOrigin,
357
- value.webAppOrigin,
358
- );
359
- if (!originUrl || new URL(originUrl).pathname !== "/") return undefined;
360
- const webAppOrigin = new URL(originUrl).origin;
361
458
  const learning = parseInspectorLearningUrl(
362
459
  value.links.learning,
363
460
  webAppOrigin,
@@ -374,6 +471,9 @@ export function parseInspectorLearningSnapshotV1(
374
471
  !learning ||
375
472
  candidates === undefined ||
376
473
  runs === undefined ||
474
+ !validLearningPath(learning, "learning") ||
475
+ (candidates !== null && !validLearningPath(candidates, "candidates")) ||
476
+ (runs !== null && !validLearningPath(runs, "runs")) ||
377
477
  (value.pendingThreadCount > 0 && runs === null) ||
378
478
  (value.pendingCandidateCount > 0 && candidates === null)
379
479
  )
@@ -374,6 +374,8 @@ test.each([
374
374
  "https://cloud.copilotkit.ai/manage",
375
375
  "https://cloud.copilotkit.ai/manage/plan",
376
376
  "http://localhost/manage",
377
+ "http://sub.localhost/manage",
378
+ "http://cpk.localhost:7066/manage",
377
379
  "http://localhost:3000/manage",
378
380
  "http://127.0.0.1:3000/manage",
379
381
  "http://[::1]:3000/manage",
@@ -402,7 +404,6 @@ test.each([
402
404
  "ftp://cloud.copilotkit.ai/manage",
403
405
  "http://cloud.copilotkit.ai/manage",
404
406
  "http://localhost.example.com/manage",
405
- "http://sub.localhost/manage",
406
407
  "http://127.0.0.2/manage",
407
408
  "http://[::2]/manage",
408
409
  "http://0.0.0.0/manage",
@@ -1,3 +1,5 @@
1
+ import { isSafeDashboardUrl } from "./dashboard-url";
2
+
1
3
  /**
2
4
  * Inspector metadata supplied by a trusted CopilotKit runtime.
3
5
  *
@@ -157,19 +159,7 @@ function parseSafeActionUrl(value: unknown): string | undefined {
157
159
  return undefined;
158
160
  }
159
161
 
160
- if (parsed.protocol === "https:") {
161
- return url;
162
- }
163
-
164
- const isLoopbackHost =
165
- parsed.hostname === "localhost" ||
166
- parsed.hostname === "127.0.0.1" ||
167
- parsed.hostname === "[::1]";
168
- if (parsed.protocol === "http:" && isLoopbackHost) {
169
- return url;
170
- }
171
-
172
- return undefined;
162
+ return isSafeDashboardUrl(parsed) ? url : undefined;
173
163
  }
174
164
 
175
165
  function parseAction(value: unknown): InspectorAction | undefined {
package/src/utils.test.ts CHANGED
@@ -33,6 +33,77 @@ describe("partialJSONParse", () => {
33
33
  test("should return {} for an empty string", () => {
34
34
  expect(partialJSONParse("")).toEqual({});
35
35
  });
36
+
37
+ test("should withhold an unterminated trailing number", () => {
38
+ expect(partialJSONParse('{"value":72,"max":1')).toEqual({ value: 72 });
39
+ });
40
+
41
+ test("should withhold a number that is still unterminated at end of input", () => {
42
+ expect(partialJSONParse('{"value":72,"max":100')).toEqual({ value: 72 });
43
+ });
44
+
45
+ test("should reveal a number once terminated", () => {
46
+ expect(partialJSONParse('{"value":72,"max":100}')).toEqual({
47
+ value: 72,
48
+ max: 100,
49
+ });
50
+ });
51
+
52
+ test("should withhold an unterminated trailing array number", () => {
53
+ expect(partialJSONParse('{"data":[10,20,3')).toEqual({ data: [10, 20] });
54
+ expect(partialJSONParse('{"data":[10,20,30]')).toEqual({
55
+ data: [10, 20, 30],
56
+ });
57
+ });
58
+
59
+ test("should withhold unterminated numbers at any depth", () => {
60
+ expect(partialJSONParse('{"nested":{"a":1,"b":2')).toEqual({
61
+ nested: { a: 1 },
62
+ });
63
+ });
64
+
65
+ test("should withhold unterminated negatives, decimals and exponents", () => {
66
+ for (const input of [
67
+ '{"x":-',
68
+ '{"x":-4',
69
+ '{"x":3.',
70
+ '{"x":3.1',
71
+ '{"x":1e',
72
+ '{"x":1e-',
73
+ ]) {
74
+ expect(partialJSONParse(input)).toEqual({});
75
+ }
76
+ });
77
+
78
+ test("should keep negative, decimal and exponent numbers once terminated", () => {
79
+ expect(partialJSONParse('{"x":-4,"y":2')).toEqual({ x: -4 });
80
+ expect(partialJSONParse('{"x":3.1,"y":2')).toEqual({ x: 3.1 });
81
+ expect(partialJSONParse('{"x":1e-3,"y":2')).toEqual({ x: 1e-3 });
82
+ });
83
+
84
+ test("should withhold a number followed only by whitespace", () => {
85
+ expect(partialJSONParse('{"max":100\n')).toEqual({});
86
+ });
87
+
88
+ test("should still allow partial strings, booleans and null", () => {
89
+ expect(partialJSONParse('{"name":"jo')).toEqual({ name: "jo" });
90
+ expect(partialJSONParse('{"value":72,"max":tru')).toEqual({
91
+ value: 72,
92
+ max: true,
93
+ });
94
+ expect(partialJSONParse('{"value":72,"max":nul')).toEqual({
95
+ value: 72,
96
+ max: null,
97
+ });
98
+ });
99
+
100
+ test("should still parse complete numbers", () => {
101
+ expect(partialJSONParse('{"value":72,"max":100}')).toEqual({
102
+ value: 72,
103
+ max: 100,
104
+ });
105
+ expect(partialJSONParse('{"pi":3.14}')).toEqual({ pi: 3.14 });
106
+ });
36
107
  });
37
108
 
38
109
  describe("safeParseToolArgs", () => {