@vellumai/assistant 0.12.1-dev.202609141913.5e16607 → 0.12.1-dev.202609142113.d1590bc

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 (118) hide show
  1. package/ARCHITECTURE.md +9 -9
  2. package/openapi.yaml +35 -2
  3. package/package.json +2 -1
  4. package/src/__tests__/anthropic-provider.test.ts +0 -63
  5. package/src/__tests__/assistant-event-hub-machine-name.test.ts +6 -7
  6. package/src/__tests__/assistant-event-hub.test.ts +44 -0
  7. package/src/__tests__/computer-use-skill-manifest-regression.test.ts +1 -1
  8. package/src/__tests__/computer-use-tools.test.ts +2 -2
  9. package/src/__tests__/heartbeat-service.test.ts +56 -40
  10. package/src/__tests__/host-cu-proxy.test.ts +539 -0
  11. package/src/__tests__/list-messages-camera-frame.test.ts +121 -0
  12. package/src/__tests__/oauth-commands-routes.test.ts +113 -0
  13. package/src/__tests__/oauth-provider-profiles.test.ts +18 -0
  14. package/src/__tests__/openai-provider.test.ts +1 -0
  15. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -0
  16. package/src/__tests__/qdrant-manager.test.ts +132 -0
  17. package/src/__tests__/scaffold-managed-skill-tool.test.ts +229 -6
  18. package/src/__tests__/skills.test.ts +9 -4
  19. package/src/__tests__/test-support/computer-use-skill-harness.ts +3 -2
  20. package/src/__tests__/unicode.test.ts +13 -0
  21. package/src/acp/agent-process.ts +2 -1
  22. package/src/agent/loop.ts +1 -0
  23. package/src/api/events/user-message-echo.ts +7 -1
  24. package/src/api/responses/conversation-message.ts +5 -0
  25. package/src/avatar/identity-avatar.ts +7 -2
  26. package/src/config/bundled-skills/computer-use/SKILL.md +20 -2
  27. package/src/config/bundled-skills/computer-use/TOOLS.json +99 -0
  28. package/src/config/bundled-skills/computer-use/tools/computer-use-sequence.ts +12 -0
  29. package/src/config/bundled-skills/media-processing/services/preprocess.ts +2 -1
  30. package/src/config/bundled-skills/media-processing/services/processing-pipeline.ts +2 -1
  31. package/src/config/bundled-skills/media-processing/tools/generate-clip.ts +2 -1
  32. package/src/config/bundled-skills/playbooks/tools/playbook-create.ts +2 -1
  33. package/src/config/bundled-skills/playbooks/tools/playbook-update.ts +2 -1
  34. package/src/config/bundled-skills/skill-management/TOOLS.json +4 -0
  35. package/src/config/bundled-skills/transcribe/tools/transcribe-media.ts +5 -2
  36. package/src/credential-health/credential-health-service.ts +11 -17
  37. package/src/daemon/conversation-error.ts +3 -2
  38. package/src/daemon/conversation-media-retry.ts +2 -1
  39. package/src/daemon/conversation-runtime-assembly.ts +2 -1
  40. package/src/daemon/conversation-surfaces.ts +5 -1
  41. package/src/daemon/dictation-profile-store.ts +2 -1
  42. package/src/daemon/handlers/shared.ts +2 -1
  43. package/src/daemon/handlers/skills.ts +6 -3
  44. package/src/daemon/host-cu-proxy.ts +186 -19
  45. package/src/daemon/host-proxy-preactivation.ts +2 -1
  46. package/src/daemon/reaction-history-render.ts +2 -1
  47. package/src/heartbeat/heartbeat-service.ts +21 -3
  48. package/src/live-voice/__tests__/live-voice-sight-frame-echo.test.ts +238 -0
  49. package/src/live-voice/live-voice-photo.ts +25 -6
  50. package/src/oauth/AGENTS.md +2 -0
  51. package/src/oauth/byo-connection.test.ts +60 -0
  52. package/src/oauth/scope-utils.ts +24 -0
  53. package/src/oauth/seed-providers.ts +39 -25
  54. package/src/persistence/conversation-queries.ts +2 -2
  55. package/src/persistence/embeddings/qdrant-manager.ts +163 -18
  56. package/src/plugins/defaults/memory/__tests__/memory-retrospective-prompt.test.ts +5 -0
  57. package/src/plugins/defaults/memory/context-search/agent-runner.ts +3 -2
  58. package/src/plugins/defaults/memory/context-search/format.ts +3 -2
  59. package/src/plugins/defaults/memory/context-search/sources/memory-v2.ts +6 -3
  60. package/src/plugins/defaults/memory/context-search/sources/workspace.ts +3 -2
  61. package/src/plugins/defaults/memory/graph/capability-seed.ts +2 -1
  62. package/src/plugins/defaults/memory/host-utils.ts +10 -0
  63. package/src/plugins/defaults/memory/memory-retrospective-prompt.ts +1 -1
  64. package/src/plugins/defaults/memory/startup.ts +22 -1
  65. package/src/plugins/defaults/memory/substrate/page-index.ts +6 -1
  66. package/src/plugins/defaults/memory/v1/graph/consolidation.ts +4 -2
  67. package/src/plugins/defaults/memory/v1/graph/extraction.ts +4 -2
  68. package/src/plugins/defaults/memory/v1/graph/retriever.ts +4 -1
  69. package/src/plugins/defaults/memory/v2/reranker.ts +6 -1
  70. package/src/plugins/defaults/memory/v3/__tests__/card.test.ts +24 -0
  71. package/src/plugins/defaults/memory/v3/__tests__/pool-select.test.ts +39 -3
  72. package/src/plugins/defaults/memory/v3/__tests__/sections.test.ts +26 -0
  73. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +30 -0
  74. package/src/plugins/defaults/memory/v3/card.ts +3 -2
  75. package/src/plugins/defaults/memory/v3/pool-select.ts +5 -3
  76. package/src/plugins/defaults/memory/v3/sections.ts +9 -3
  77. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +5 -2
  78. package/src/providers/__tests__/retry-outbound-sanitize.test.ts +176 -0
  79. package/src/providers/anthropic/client.ts +0 -47
  80. package/src/providers/openai/__tests__/chat-completions-output-token-limit.test.ts +141 -0
  81. package/src/providers/openai/chat-completions-provider.ts +20 -1
  82. package/src/providers/openrouter/client.ts +20 -0
  83. package/src/providers/outbound-request-sanitize.ts +96 -0
  84. package/src/providers/retry.ts +24 -3
  85. package/src/providers/unparseable-tool-args.ts +5 -1
  86. package/src/runtime/AGENTS.md +1 -1
  87. package/src/runtime/__tests__/host-observe.test.ts +40 -1
  88. package/src/runtime/agent-wake.ts +2 -1
  89. package/src/runtime/assistant-event-hub.ts +21 -3
  90. package/src/runtime/host-observe.ts +11 -1
  91. package/src/runtime/routes/conversation-routes.ts +16 -3
  92. package/src/runtime/routes/diagnostics-routes.ts +6 -1
  93. package/src/runtime/routes/events-routes.ts +4 -0
  94. package/src/runtime/routes/host-cu-routes.ts +6 -0
  95. package/src/runtime/routes/oauth-commands-routes.ts +36 -0
  96. package/src/runtime/routes/workspace-routes.test.ts +55 -26
  97. package/src/runtime/routes/workspace-routes.ts +46 -63
  98. package/src/runtime/routes/workspace-tree-walk.test.ts +244 -0
  99. package/src/runtime/routes/workspace-tree-walk.ts +240 -0
  100. package/src/runtime/routes/workspace-utils.ts +17 -0
  101. package/src/schedule/run-script.ts +2 -1
  102. package/src/schedule/schedule-store.ts +9 -2
  103. package/src/security/untrusted-content.ts +3 -1
  104. package/src/tools/__tests__/side-effect-abort-guard.test.ts +1 -0
  105. package/src/tools/browser/browser-execution.ts +1 -1
  106. package/src/tools/browser/cdp-client/accessibility-snapshot.ts +9 -3
  107. package/src/tools/browser/cdp-client/cdp-inspect/discovery.ts +2 -1
  108. package/src/tools/browser/cdp-client/extension-cdp-client.ts +3 -2
  109. package/src/tools/browser/network-recorder.ts +2 -1
  110. package/src/tools/computer-use/definitions.ts +117 -0
  111. package/src/tools/filesystem/search.ts +2 -1
  112. package/src/tools/network/web-search.ts +6 -1
  113. package/src/tools/skills/scaffold-managed.ts +61 -3
  114. package/src/types/host-capabilities.ts +5 -3
  115. package/src/util/unicode.ts +15 -1
  116. package/src/watch/watch-timeline.ts +2 -2
  117. package/src/workflows/run-manager.ts +2 -1
  118. package/src/workspace/git-service.ts +1 -1
@@ -1,6 +1,7 @@
1
1
  import { readdir, readFile, realpath, stat } from "node:fs/promises";
2
2
  import { extname, isAbsolute, join, relative, sep } from "node:path";
3
3
 
4
+ import { safeStringSlice } from "../../host-utils.js";
4
5
  import { isPathInsideRoot } from "../../path-containment.js";
5
6
  import type {
6
7
  RecallEvidence,
@@ -924,7 +925,7 @@ function buildExcerpt(lines: readonly string[], lineIndex: number): string {
924
925
  return focusedLine;
925
926
  }
926
927
 
927
- return `${focusedLine.slice(0, EXCERPT_MAX_CHARS - 3).trimEnd()}...`;
928
+ return `${safeStringSlice(focusedLine, 0, EXCERPT_MAX_CHARS - 3).trimEnd()}...`;
928
929
  }
929
930
 
930
931
  function buildSectionExcerpt(
@@ -942,7 +943,7 @@ function buildSectionExcerpt(
942
943
  return excerpt;
943
944
  }
944
945
 
945
- return `${excerpt.slice(0, SECTION_EXCERPT_MAX_CHARS - 3).trimEnd()}...`;
946
+ return `${safeStringSlice(excerpt, 0, SECTION_EXCERPT_MAX_CHARS - 3).trimEnd()}...`;
946
947
  }
947
948
 
948
949
  function buildStructuredJsonExcerpt(contents: string): string {
@@ -26,6 +26,7 @@ import {
26
26
  getCachedCatalogSync,
27
27
  getCatalog,
28
28
  } from "../../../../skills/catalog-cache.js";
29
+ import { safeStringSlice } from "../host-utils.js";
29
30
  import { getLogger } from "../logging.js";
30
31
  import { memoryDbOrNull } from "../memory-db.js";
31
32
  import type { SkillCapabilityInput } from "../substrate/skill-content.js";
@@ -245,7 +246,7 @@ function buildSkillContent(input: SkillCapabilityInput): string {
245
246
  content += ` Avoid when: ${input.avoidWhen.join("; ")}.`;
246
247
  }
247
248
  if (content.length > 500) {
248
- content = content.slice(0, 500);
249
+ content = safeStringSlice(content, 0, 500);
249
250
  }
250
251
  return content;
251
252
  }
@@ -25,6 +25,7 @@ import type { SqliteRetryOptions } from "../../../util/sqlite-retry.js";
25
25
  import * as hostSqliteRetry from "../../../util/sqlite-retry.js";
26
26
  import * as hostStripCommentLines from "../../../util/strip-comment-lines.js";
27
27
  import * as hostTruncate from "../../../util/truncate.js";
28
+ import * as hostUnicode from "../../../util/unicode.js";
28
29
  import * as hostWorkerCompute from "../../../util/worker-compute.js";
29
30
  import * as hostWorkerMemory from "../../../util/worker-memory.js";
30
31
 
@@ -76,6 +77,15 @@ export function truncate(str: string, maxLen: number, suffix?: string): string {
76
77
  : hostTruncate.truncate(str, maxLen, suffix);
77
78
  }
78
79
 
80
+ /** `String.prototype.slice` that never cuts a UTF-16 surrogate pair in half. */
81
+ export function safeStringSlice(
82
+ str: string,
83
+ start?: number,
84
+ end?: number,
85
+ ): string {
86
+ return hostUnicode.safeStringSlice(str, start, end);
87
+ }
88
+
79
89
  export function workerMemoryEnv(): Record<string, string | undefined> {
80
90
  return hostWorkerMemory.workerMemoryEnv();
81
91
  }
@@ -223,7 +223,7 @@ If your review window contains a PROCEDURE you actually carried out — a sequen
223
223
 
224
224
  When you do capture a procedure:
225
225
 
226
- 1. Deduplicate against existing skills first. Call \`find_similar_skills\` with the procedure's goal as its \`goal\` argument. Each hit carries a \`source\` (bundled, managed, plugin, workspace, or extra), and a managed hit also carries \`author\` (\`"assistant"\` if you authored it, \`"user"\` if a person did, omitted if untagged). You may only overwrite or refine a skill YOU authored — a hit with \`source: "managed"\` AND \`author: "assistant"\`. ANY other hit means the procedure is ALREADY COVERED: a non-managed source (bundled, plugin, workspace, or extra), OR a managed skill that is NOT \`author: "assistant"\` (a person wrote it, or it is untagged). For an ALREADY COVERED hit do not \`overwrite\` it, do not shadow it by creating a skill with its \`skill_id\`, and do not create a near-duplicate — skip it. Only when a returned skill is one of your own (\`source: "managed"\`, \`author: "assistant"\`) and is the SAME procedure, UPDATE it: call \`scaffold_managed_skill\` with that \`skill_id\` and \`overwrite: true\`, rewriting \`body_markdown\` from what you actually observed in the trace. Only CREATE a new skill (fresh \`skill_id\`) when no existing skill of any source covers the procedure. Bias strongly toward reusing or refining your own skills over spawning near-duplicates.
226
+ 1. Deduplicate against existing skills first. Call \`find_similar_skills\` with the procedure's goal as its \`goal\` argument. Each hit carries a \`source\` (bundled, managed, plugin, workspace, or extra), and a managed hit also carries \`author\` (\`"assistant"\` if you authored it, \`"user"\` if a person did, omitted if untagged). You may only overwrite or refine a skill YOU authored: a hit with \`source: "managed"\` AND \`author: "assistant"\`. ANY other hit means the procedure is ALREADY COVERED: a non-managed source (bundled, plugin, workspace, or extra), OR a managed skill that is NOT \`author: "assistant"\` (a person wrote it, or it is untagged). For an ALREADY COVERED hit do not \`overwrite\` it, do not shadow it by creating a skill with its \`skill_id\`, and do not create a near-duplicate. Skip it. Only when a returned skill is one of your own (\`source: "managed"\`, \`author: "assistant"\`) and is the SAME procedure, UPDATE it: call \`scaffold_managed_skill\` with that \`skill_id\` and \`overwrite: true\`, rewriting \`body_markdown\` from what you actually observed in the trace, and pass \`change_summary\` (the update is rejected without it): one or two short sentences (under 200 characters) for the person who reads the "Skill updated" notice, naming what you changed and what in the trace prompted it (for example "Added the retry after an expired session and the export endpoint that held steady."). The notice shows nothing else about the change, so name the concrete step, value, or gotcha rather than saying the skill was refined. Only CREATE a new skill (fresh \`skill_id\`) when no existing skill of any source covers the procedure. Bias strongly toward reusing or refining your own skills over spawning near-duplicates.
227
227
 
228
228
  2. Capture procedure-scoped knowledge alongside the body. Failure modes, gotchas, and cached values you observed in the trace (error signatures and how you recovered, preconditions, IDs/paths/endpoints that held steady) belong in companion files passed via \`scaffold_managed_skill\`'s \`files\` input (for example \`references/failure-modes.md\`), and the SKILL.md body should reference them so a future load surfaces them.
229
229
 
@@ -41,11 +41,15 @@ import {
41
41
  clearRebuildSentinel,
42
42
  initQdrantClient,
43
43
  } from "../../../persistence/embeddings/qdrant-client.js";
44
- import { createQdrantManager } from "../../../persistence/embeddings/qdrant-manager.js";
44
+ import {
45
+ createQdrantManager,
46
+ describeQdrantStartFailure,
47
+ } from "../../../persistence/embeddings/qdrant-manager.js";
45
48
  import {
46
49
  enqueueMemoryJob,
47
50
  isMemoryEnabled,
48
51
  } from "../../../persistence/jobs-store.js";
52
+ import { recordWatchdogEvent } from "../../../telemetry/watchdog-events-store.js";
49
53
  import { resolveQdrantUrl } from "./embeddings.js";
50
54
  import { startMemoryJobsWorker } from "./jobs-worker.js";
51
55
  import { getLogger } from "./logging.js";
@@ -92,6 +96,23 @@ export async function runMemoryStartup(config: AssistantConfig): Promise<void> {
92
96
  { err },
93
97
  "Qdrant failed to start after all attempts — memory features will be unavailable",
94
98
  );
99
+ // Fleet-wide record of the failure: the step, the exit code and
100
+ // Qdrant's own reason line, bounded to telemetry-safe metadata by
101
+ // `describeQdrantStartFailure`. Observational only: the outbox insert
102
+ // can throw on a locked or half-migrated telemetry DB, and this path
103
+ // must still reach the worker start below.
104
+ try {
105
+ recordWatchdogEvent({
106
+ checkName: "qdrant_start_failed",
107
+ value: attempt,
108
+ detail: { attempts: attempt, ...describeQdrantStartFailure(err) },
109
+ });
110
+ } catch (telemetryErr) {
111
+ log.warn(
112
+ { err: telemetryErr },
113
+ "Qdrant start failure could not be recorded to telemetry",
114
+ );
115
+ }
95
116
  }
96
117
  }
97
118
  }
@@ -19,6 +19,7 @@
19
19
  * concept pages or seeded skill entries change.
20
20
  */
21
21
 
22
+ import { safeStringSlice } from "../host-utils.js";
22
23
  import { getLogger } from "../logging.js";
23
24
  import {
24
25
  CLI_COMMAND_SLUG_PREFIX,
@@ -51,7 +52,11 @@ const SUMMARY_MAX_LENGTH = 200;
51
52
  * and corrupt the format the router parses.
52
53
  */
53
54
  function normalizeSummary(raw: string): string {
54
- return raw.replace(/\s+/g, " ").trim().slice(0, SUMMARY_MAX_LENGTH);
55
+ return safeStringSlice(
56
+ raw.replace(/\s+/g, " ").trim(),
57
+ 0,
58
+ SUMMARY_MAX_LENGTH,
59
+ );
55
60
  }
56
61
 
57
62
  /**
@@ -26,7 +26,7 @@ import {
26
26
  } from "../../graph/store.js";
27
27
  import type { MemoryNode } from "../../graph/types.js";
28
28
  import { isCapabilityNode } from "../../graph/types.js";
29
- import { BackendUnavailableError } from "../../host-utils.js";
29
+ import { BackendUnavailableError, safeStringSlice } from "../../host-utils.js";
30
30
  import { extractToolUse, userMessage } from "../../llm-helpers.js";
31
31
  import { getLogger } from "../../logging.js";
32
32
  import {
@@ -268,7 +268,9 @@ async function identifyDuplicateGroups(
268
268
  const listing = nodes
269
269
  .map((n) => {
270
270
  const preview =
271
- n.content.length > 100 ? n.content.slice(0, 100) + "…" : n.content;
271
+ n.content.length > 100
272
+ ? safeStringSlice(n.content, 0, 100) + "…"
273
+ : n.content;
272
274
  return `[${n.id}] ${preview}`;
273
275
  })
274
276
  .join("\n");
@@ -46,7 +46,7 @@ import type {
46
46
  SourceType,
47
47
  TriggerType,
48
48
  } from "../../graph/types.js";
49
- import { BackendUnavailableError } from "../../host-utils.js";
49
+ import { BackendUnavailableError, safeStringSlice } from "../../host-utils.js";
50
50
  import { extractToolUse, userMessage } from "../../llm-helpers.js";
51
51
  import { getLogger } from "../../logging.js";
52
52
  import { buildIdentityContext } from "../identity-context.js";
@@ -1617,7 +1617,9 @@ async function findCandidateNodes(
1617
1617
  await import("../../../../../persistence/embeddings/embed.js");
1618
1618
  const searchText =
1619
1619
  transcript.length > 3000
1620
- ? transcript.slice(0, 1500) + "\n...\n" + transcript.slice(-1500)
1620
+ ? safeStringSlice(transcript, 0, 1500) +
1621
+ "\n...\n" +
1622
+ safeStringSlice(transcript, transcript.length - 1500)
1621
1623
  : transcript;
1622
1624
 
1623
1625
  try {
@@ -33,6 +33,7 @@ import type {
33
33
  ScoredNode,
34
34
  } from "../../graph/types.js";
35
35
  import { isCapabilityNode } from "../../graph/types.js";
36
+ import { safeStringSlice } from "../../host-utils.js";
36
37
  import { extractToolUse, userMessage } from "../../llm-helpers.js";
37
38
  import { getLogger } from "../../logging.js";
38
39
  import { searchGraphNodes } from "./graph-search.js";
@@ -491,7 +492,9 @@ export async function loadContextMemory(
491
492
  try {
492
493
  const queryText = opts.recentSummaries.join("\n\n");
493
494
  const truncated =
494
- queryText.length > 3000 ? queryText.slice(0, 3000) : queryText;
495
+ queryText.length > 3000
496
+ ? safeStringSlice(queryText, 0, 3000)
497
+ : queryText;
495
498
  contextQueryText = truncated;
496
499
  const result = await embedWithRetry(opts.config, [truncated], {
497
500
  signal: opts.signal,
@@ -3,6 +3,7 @@
3
3
  import { createHash } from "node:crypto";
4
4
 
5
5
  import type { AssistantConfig } from "../../../../config/types.js";
6
+ import { safeStringSlice } from "../host-utils.js";
6
7
  import { getLogger } from "../logging.js";
7
8
  import { getWorkspaceDir } from "../paths.js";
8
9
  import { readPage } from "../substrate/page-store.js";
@@ -57,7 +58,11 @@ function buildPassage(slug: string, body: string): string {
57
58
  const blank = trimmed.search(/\n\s*\n/);
58
59
  const para = blank === -1 ? trimmed : trimmed.slice(0, blank);
59
60
  const stripped = para.replace(/^#+\s.*\n/, "").trim();
60
- const compact = stripped.replace(/\s+/g, " ").slice(0, PASSAGE_CHAR_CAP);
61
+ const compact = safeStringSlice(
62
+ stripped.replace(/\s+/g, " "),
63
+ 0,
64
+ PASSAGE_CHAR_CAP,
65
+ );
61
66
  return `${slug}\n${compact}`;
62
67
  }
63
68
 
@@ -6,6 +6,8 @@
6
6
 
7
7
  import { describe, expect, test } from "bun:test";
8
8
 
9
+ import { stripOrphanedSurrogates } from "../../../../../util/unicode.js";
10
+ import { LINK_SEPARATOR } from "../../substrate/page-links.js";
9
11
  import { renderCard } from "../card.js";
10
12
 
11
13
  const PAGE = `---
@@ -73,6 +75,28 @@ Lead paragraph for page a.
73
75
  expect(line.length).toBeLessThan(300);
74
76
  });
75
77
 
78
+ test("capping a `current:` value never splits an emoji at the cap", () => {
79
+ // 279 BMP characters put the 280-character cap inside the emoji's pair.
80
+ const current = `${"x".repeat(279)}🎉 trailing`;
81
+ const card = renderCard(
82
+ "page-a",
83
+ `---\ncurrent: "${current}"\n---\n\nLead.\n`,
84
+ );
85
+ const line = card.split("\n")[1]!;
86
+ expect(stripOrphanedSurrogates(line)).toBe(line);
87
+ expect(line).toBe(`[current: ${"x".repeat(279)}…]`);
88
+ });
89
+
90
+ test("capping a link note never splits an emoji at the cap", () => {
91
+ const note = `${"n".repeat(79)}🎉 trailing`;
92
+ const card = renderCard(
93
+ "page-a",
94
+ `---\nkind: index\nlinks:\n - "other${LINK_SEPARATOR}${note}"\n---\n\nLead.\n`,
95
+ );
96
+ expect(stripOrphanedSurrogates(card)).toBe(card);
97
+ expect(card).toContain(`other${LINK_SEPARATOR}${"n".repeat(79)}…`);
98
+ });
99
+
76
100
  test("the `status:` draft marker does NOT render as a card line", () => {
77
101
  const card = renderCard("page-a", `---\nstatus: cc-draft\n---\n\nLead.\n`);
78
102
  expect(card).not.toContain("cc-draft");
@@ -41,6 +41,7 @@ import type {
41
41
 
42
42
  import { OpenRouterProvider } from "../../../../../providers/openrouter/client.js";
43
43
  import { ProviderError } from "../../../../../util/errors.js";
44
+ import { stripOrphanedSurrogates } from "../../../../../util/unicode.js";
44
45
  import { sectionHeadLine } from "../sections.js";
45
46
  import type { MemoryRoutingTurn, Section } from "../types.js";
46
47
 
@@ -843,6 +844,41 @@ describe("selectPool: sections and keyword-in-context snippets", () => {
843
844
  true,
844
845
  );
845
846
  });
847
+ test("a window whose edges land inside an emoji keeps both pairs whole and the request well-formed", async () => {
848
+ providerStub = makeProvider(toolUseResponse({ ids: [] }));
849
+ // 200 emoji (400 code units) on each side of the term, offset so that a
850
+ // code-unit window centered on the term starts and ends mid-pair. A
851
+ // window cut there carries half a pair on each edge, which strict
852
+ // provider parsers reject once JSON.stringify escapes each orphan.
853
+ const emoji = "😀".repeat(200);
854
+ const body = `${emoji}y turnip ${emoji}`;
855
+ const term = body.indexOf("turnip");
856
+ const naiveStart = term + 3 - 150;
857
+ const naive = body.slice(naiveStart, naiveStart + 300);
858
+ expect(stripOrphanedSurrogates(naive)).not.toBe(naive);
859
+ const section = sectionOf("page-a", "Rollout", body);
860
+ await selectPool(
861
+ finderOnly({
862
+ slug: "page-a",
863
+ descriptor: section.text,
864
+ section,
865
+ terms: ["turnip"],
866
+ }),
867
+ makeTurn("turnip?"),
868
+ );
869
+ const [block] = sentBlocks();
870
+ expect(stripOrphanedSurrogates(block.text)).toBe(block.text);
871
+ const line = block.text
872
+ .split("\n")
873
+ .find((l) => l.startsWith("[1] page-a "))!;
874
+ expect(line).toContain("§Rollout: … ");
875
+ expect(line).toContain("turnip");
876
+ expect(line.endsWith(" …")).toBe(true);
877
+ // The window stays bounded: at most one code unit shorter on each edge.
878
+ const windowStart = line.indexOf("… ") + "… ".length;
879
+ expect(line.length - windowStart).toBeLessThanOrEqual(300 + " …".length);
880
+ expect(line.length - windowStart).toBeGreaterThanOrEqual(298 + " …".length);
881
+ });
846
882
  });
847
883
 
848
884
  // ---------------------------------------------------------------------------
@@ -923,9 +959,9 @@ describe("selectPool: cataloged thinking and forced-tool compatibility", () => {
923
959
  effort: "high",
924
960
  summary: "detailed",
925
961
  });
926
- expect(
927
- warnPayloads().filter((p) => p.reason === "provider_error"),
928
- ).toEqual([]);
962
+ expect(warnPayloads().filter((p) => p.reason === "provider_error")).toEqual(
963
+ [],
964
+ );
929
965
 
930
966
  // Structured selection survived: ids [3] is the topic-x finder line.
931
967
  expect(selection.keptAll).toBe(false);
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
 
3
+ import { stripOrphanedSurrogates } from "../../../../../util/unicode.js";
3
4
  import {
4
5
  buildSectionIndex,
5
6
  leadSectionOfBody,
@@ -108,6 +109,31 @@ describe("buildSectionIndex", () => {
108
109
  }
109
110
  });
110
111
 
112
+ test("a hard split never lands inside a surrogate pair and loses no text", async () => {
113
+ // One unbroken line of emoji longer than the window, offset by one BMP
114
+ // character so the window boundary falls between a pair's halves.
115
+ const unbroken = `y${"😀".repeat(SECTION_CHUNK_CHARS)}`;
116
+ const index = await buildSectionIndex(
117
+ ["page-a"],
118
+ reader({ "page-a": `## Big\n${unbroken}` }),
119
+ );
120
+
121
+ const big = index.sections.filter((s) => s.title === "Big");
122
+ expect(big.length).toBeGreaterThan(1);
123
+ for (const chunk of big) {
124
+ expect(chunk.text.length).toBeLessThanOrEqual(SECTION_CHUNK_CHARS);
125
+ expect(stripOrphanedSurrogates(chunk.text)).toBe(chunk.text);
126
+ }
127
+ expect(big.map(sectionBody).join("")).toBe(unbroken);
128
+ });
129
+
130
+ test("a capped head-line title never ends in half an emoji", () => {
131
+ const title = `${"t".repeat(199)}🎉 more`;
132
+ const head = sectionHeadLine("page-a", title);
133
+ expect(stripOrphanedSurrogates(head)).toBe(head);
134
+ expect(head).toBe(`page-a - ${"t".repeat(199)}`);
135
+ });
136
+
111
137
  test("a heading longer than the window still chunks by near-window bodies; the key keeps the full title", async () => {
112
138
  const title = "H".repeat(SECTION_CHUNK_CHARS + 100);
113
139
  const body = "b".repeat(SECTION_CHUNK_CHARS * 2);
@@ -38,6 +38,7 @@ import { ESCALATION_CONTINUATION_CONTENT } from "../../../../../calls/voice-tria
38
38
  import { MemoryV3GateSchema } from "../../../../../config/schemas/memory-v3.js";
39
39
  import { ensureMemoryV3SelectionsSchema } from "../../../../../persistence/migrations/338-move-memory-v3-selections-to-memory-db.js";
40
40
  import * as schema from "../../../../../persistence/schema/index.js";
41
+ import { stripOrphanedSurrogates } from "../../../../../util/unicode.js";
41
42
  import type { HotSetEntry, HotSetOptions } from "../hot-set.js";
42
43
  import type { OrchestrateResult } from "../orchestrate.js";
43
44
  import {
@@ -1083,6 +1084,35 @@ describe("memory-v3 engine", () => {
1083
1084
  expect(turn.previousAssistantMessage).toBeUndefined();
1084
1085
  });
1085
1086
 
1087
+ test("the reply tail never starts inside a surrogate pair", async () => {
1088
+ // 1300 emoji then one BMP character: the 2500-code-unit tail would start
1089
+ // on a low surrogate, an orphan the embedding request's parser rejects.
1090
+ const reply = `${"😀".repeat(1300)}a`;
1091
+ messages = [
1092
+ {
1093
+ role: "user",
1094
+ content: JSON.stringify([{ type: "text", text: "first question" }]),
1095
+ },
1096
+ {
1097
+ role: "assistant",
1098
+ content: JSON.stringify([{ type: "text", text: reply }]),
1099
+ },
1100
+ {
1101
+ role: "user",
1102
+ content: JSON.stringify([{ type: "text", text: "and now this" }]),
1103
+ },
1104
+ ];
1105
+ await observeTurn("conv-1", 1);
1106
+
1107
+ const turn = (
1108
+ orchestrateSpy.mock.calls as unknown as unknown[][]
1109
+ )[0]![0] as MemoryRoutingTurn;
1110
+ const tail = turn.previousAssistantMessage!;
1111
+ expect(stripOrphanedSurrogates(tail)).toBe(tail);
1112
+ expect(tail.length).toBeLessThanOrEqual(2500);
1113
+ expect(reply.endsWith(tail)).toBe(true);
1114
+ });
1115
+
1086
1116
  test("a page with lines from two lanes is attributed the lane of the line whose section was selected", () => {
1087
1117
  const bulk: Section = {
1088
1118
  article: "page-two",
@@ -1,4 +1,5 @@
1
1
  import { FRONTMATTER_REGEX, parseFrontmatterFields } from "../frontmatter.js";
2
+ import { safeStringSlice } from "../host-utils.js";
2
3
  import { injectedConceptHeader } from "../substrate/injected-block-slugs.js";
3
4
  import { LINK_SEPARATOR, parseLinkEntry } from "../substrate/page-links.js";
4
5
  import type { Slug } from "./types.js";
@@ -38,7 +39,7 @@ function renderLinkEntry(entry: string): string {
38
39
  }
39
40
  const note =
40
41
  description.length > LINK_NOTE_MAX_CHARS
41
- ? `${description.slice(0, LINK_NOTE_MAX_CHARS).trimEnd()}…`
42
+ ? `${safeStringSlice(description, 0, LINK_NOTE_MAX_CHARS).trimEnd()}…`
42
43
  : description;
43
44
  return `${target}${LINK_SEPARATOR}${note}`;
44
45
  }
@@ -103,7 +104,7 @@ export function renderCurrentLine(
103
104
  }
104
105
  const capped =
105
106
  collapsed.length > CURRENT_MAX_CHARS
106
- ? `${collapsed.slice(0, CURRENT_MAX_CHARS).trimEnd()}…`
107
+ ? `${safeStringSlice(collapsed, 0, CURRENT_MAX_CHARS).trimEnd()}…`
107
108
  : collapsed;
108
109
  return `[current: ${capped}]`;
109
110
  }
@@ -57,7 +57,7 @@ import { z } from "zod";
57
57
 
58
58
  import { classifyConversationError } from "../../../../daemon/conversation-error.js";
59
59
  import type { PendingConversationNotice } from "../../../../daemon/conversation-notices.js";
60
- import { redactLogString, truncate } from "../host-utils.js";
60
+ import { redactLogString, safeStringSlice, truncate } from "../host-utils.js";
61
61
  import {
62
62
  cachedTextBlock,
63
63
  extractToolUse,
@@ -276,7 +276,9 @@ function oneLine(text: string): string {
276
276
  * `§<title>: … <window> …`, the window being up to {@link SNIPPET_MAX_CHARS}
277
277
  * of the one-line section body centered on the first occurrence of the
278
278
  * best-contributing query term that occurs in it (the lead, titled `""`,
279
- * renders the window alone). `undefined` when no term occurs in the body.
279
+ * renders the window alone). The window edges never split a surrogate pair:
280
+ * an orphaned half is invalid UTF-16 and strict provider parsers reject the
281
+ * whole request. `undefined` when no term occurs in the body.
280
282
  */
281
283
  function renderKeywordInContext(
282
284
  section: Section,
@@ -299,7 +301,7 @@ function renderKeywordInContext(
299
301
  const end = Math.min(body.length, start + SNIPPET_MAX_CHARS);
300
302
  const window = [
301
303
  start > 0 ? "… " : "",
302
- body.slice(start, end).trim(),
304
+ safeStringSlice(body, start, end).trim(),
303
305
  end < body.length ? " …" : "",
304
306
  ].join("");
305
307
  const title = section.title.trim();
@@ -1,3 +1,4 @@
1
+ import { safeStringSlice } from "../host-utils.js";
1
2
  import type { Section, SectionIndex, Slug } from "./types.js";
2
3
 
3
4
  /**
@@ -44,7 +45,7 @@ function lastSlugSegment(slug: Slug): string {
44
45
  * {@link sectionBody}.
45
46
  */
46
47
  export function sectionHeadLine(article: Slug, title: string): string {
47
- return `${lastSlugSegment(article)} - ${title.slice(0, SECTION_HEAD_TITLE_CHARS)}`;
48
+ return `${lastSlugSegment(article)} - ${safeStringSlice(title, 0, SECTION_HEAD_TITLE_CHARS)}`;
48
49
  }
49
50
 
50
51
  /**
@@ -95,7 +96,9 @@ export function splitIntoRawSections(body: string): RawSection[] {
95
96
  /**
96
97
  * Split `text` into chunks no longer than `limit`, preferring to break on
97
98
  * newlines so chunks stay readable. A single line longer than the limit is
98
- * hard-split at the limit. Order is preserved.
99
+ * hard-split at the limit, backed off one code unit when the limit would cut
100
+ * a surrogate pair (an orphaned half is invalid UTF-16 that strict provider
101
+ * parsers reject). Order is preserved.
99
102
  */
100
103
  function chunkText(text: string, limit: number): string[] {
101
104
  if (text.length <= limit) {
@@ -109,7 +112,10 @@ function chunkText(text: string, limit: number): string[] {
109
112
  const newlineBreak = window.lastIndexOf("\n");
110
113
  // Only break on a newline if it leaves a non-trivial chunk; otherwise hard
111
114
  // split at the window boundary to guarantee forward progress.
112
- const breakAt = newlineBreak > 0 ? newlineBreak : limit;
115
+ const breakAt =
116
+ newlineBreak > 0
117
+ ? newlineBreak
118
+ : Math.max(1, safeStringSlice(remaining, 0, limit).length);
113
119
  chunks.push(remaining.slice(0, breakAt));
114
120
  remaining = remaining.slice(breakAt).replace(/^\n/, "");
115
121
  }
@@ -44,7 +44,7 @@ import {
44
44
  timeLatencySubSpan,
45
45
  } from "../../../../daemon/turn-latency-sub-spans.js";
46
46
  import { enqueueMemoryJob } from "../../../../persistence/jobs-store.js";
47
- import { stripCommentLines } from "../host-utils.js";
47
+ import { safeStringSlice, stripCommentLines } from "../host-utils.js";
48
48
  import { getLogger } from "../logging.js";
49
49
  import { type MemorySqlite, memorySqliteOrNull } from "../memory-db.js";
50
50
  import { getWorkspaceDir, getWorkspacePromptPath } from "../paths.js";
@@ -578,7 +578,10 @@ async function buildShadowTurn(
578
578
  }
579
579
  const text = stringifyMessageContent(rows[i]!.content);
580
580
  if (text.length > 0) {
581
- previousAssistantMessage = text.slice(-REPLY_QUERY_TAIL_CHARS);
581
+ previousAssistantMessage = safeStringSlice(
582
+ text,
583
+ Math.max(0, text.length - REPLY_QUERY_TAIL_CHARS),
584
+ );
582
585
  break;
583
586
  }
584
587
  }