mixdog 1.4.4 → 1.4.5

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 (218) hide show
  1. package/package.json +1 -2
  2. package/src/cli.mjs +5 -1
  3. package/src/defaults/shipped-history.json +26 -2
  4. package/src/defaults/skills/browser-use/SKILL.md +148 -273
  5. package/src/defaults/skills/browser-use/references/devtools.md +14 -0
  6. package/src/defaults/skills/browser-use/references/page-flows.md +66 -0
  7. package/src/defaults/skills/browser-use/references/sign-in.md +70 -0
  8. package/src/defaults/skills/code-tidy/SKILL.md +60 -84
  9. package/src/defaults/skills/code-tidy/references/agent-cleanup.md +27 -2
  10. package/src/defaults/skills/computer-use/SKILL.md +145 -240
  11. package/src/defaults/skills/computer-use/references/flows.md +35 -0
  12. package/src/defaults/skills/computer-use/references/operations.md +22 -0
  13. package/src/defaults/skills/computer-use/references/platforms.md +12 -0
  14. package/src/defaults/skills/docx/SKILL.md +23 -31
  15. package/src/defaults/skills/docx/references/native-authoring.md +26 -3
  16. package/src/defaults/skills/docx/references/redlining.md +15 -0
  17. package/src/defaults/skills/image/SKILL.md +37 -77
  18. package/src/defaults/skills/image/references/prompt-forms.md +51 -0
  19. package/src/defaults/skills/image/references/text.md +6 -0
  20. package/src/defaults/skills/local-provider/SKILL.md +75 -105
  21. package/src/defaults/skills/local-provider/references/lifecycle.md +14 -0
  22. package/src/defaults/skills/local-provider/references/maintenance.md +19 -0
  23. package/src/defaults/skills/local-provider/references/recovery.md +30 -0
  24. package/src/defaults/skills/memory-management/SKILL.md +16 -20
  25. package/src/defaults/skills/pdf/SKILL.md +21 -23
  26. package/src/defaults/skills/pdf/references/blocks.md +20 -0
  27. package/src/defaults/skills/pdf/references/forms.md +12 -0
  28. package/src/defaults/skills/pdf/references/html.md +2 -2
  29. package/src/defaults/skills/pdf/references/ocr.md +7 -0
  30. package/src/defaults/skills/pdf/references/security.md +8 -0
  31. package/src/defaults/skills/pptx/SKILL.md +30 -109
  32. package/src/defaults/skills/pptx/references/audit.md +45 -0
  33. package/src/defaults/skills/pptx/references/brief-critique.md +47 -0
  34. package/src/defaults/skills/pptx/references/editing.md +24 -0
  35. package/src/defaults/skills/pptx/references/html.md +1 -1
  36. package/src/defaults/skills/pptx/references/script.md +33 -0
  37. package/src/defaults/skills/setup/SKILL.md +34 -102
  38. package/src/defaults/skills/setup/references/actions.md +72 -13
  39. package/src/defaults/skills/setup/references/surfaces.md +23 -8
  40. package/src/defaults/skills/setup-guide/SKILL.md +28 -115
  41. package/src/defaults/skills/setup-guide/references/features.md +36 -0
  42. package/src/defaults/skills/setup-guide/references/glossary.md +38 -0
  43. package/src/defaults/skills/setup-guide/references/workflow-models.md +62 -0
  44. package/src/defaults/skills/test-suite/SKILL.md +15 -127
  45. package/src/defaults/skills/test-suite/references/case-management.md +17 -9
  46. package/src/defaults/skills/test-suite/references/diagnose.md +23 -0
  47. package/src/defaults/skills/test-suite/references/prune.md +27 -0
  48. package/src/defaults/skills/test-suite/references/write.md +44 -0
  49. package/src/defaults/skills/video/SKILL.md +28 -42
  50. package/src/defaults/skills/video/references/prompting.md +31 -0
  51. package/src/defaults/skills/visualize/SKILL.md +73 -107
  52. package/src/defaults/skills/visualize/references/craft.md +1 -2
  53. package/src/defaults/skills/visualize/references/feedback.md +36 -0
  54. package/src/defaults/skills/visualize/references/showing.md +13 -0
  55. package/src/defaults/skills/xlsx/SKILL.md +23 -50
  56. package/src/defaults/skills/xlsx/references/editing.md +15 -0
  57. package/src/defaults/skills/xlsx/references/model-conventions.md +1 -1
  58. package/src/defaults/skills/xlsx/references/recalculation.md +37 -0
  59. package/src/defaults/skills/xlsx/references/report-design.md +18 -2
  60. package/src/lib/keychain-cjs.cjs +22 -1
  61. package/src/lib/rules-builder.cjs +1 -1
  62. package/src/rules/agent/AGENT.md +3 -0
  63. package/src/rules/lead/LEAD.md +3 -1
  64. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +8 -30
  65. package/src/runtime/agent/orchestrator/agent-runtime/title-completion.mjs +5 -0
  66. package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +21 -2
  67. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +3 -0
  68. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +2 -2
  69. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +2 -0
  70. package/src/runtime/agent/orchestrator/providers/anthropic-message-threads.mjs +583 -0
  71. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  72. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +81 -19
  73. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +180 -13
  74. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +56 -6
  75. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +4 -2
  76. package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +6 -6
  77. package/src/runtime/agent/orchestrator/providers/gemini-model-redirect.mjs +44 -0
  78. package/src/runtime/agent/orchestrator/providers/gemini-reasoning-relay.mjs +5 -0
  79. package/src/runtime/agent/orchestrator/providers/gemini-request-body.mjs +34 -5
  80. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +10 -0
  81. package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +11 -6
  82. package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -100
  83. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +3 -227
  84. package/src/runtime/agent/orchestrator/providers/gemini.mjs +226 -118
  85. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +11 -1
  86. package/src/runtime/agent/orchestrator/providers/lib/claude-bridge-schema.mjs +15 -3
  87. package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +2 -1
  88. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +5 -28
  89. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +50 -28
  90. package/src/runtime/agent/orchestrator/providers/openai-ws-stream/socket-handlers.mjs +14 -10
  91. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +1 -3
  92. package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs +8 -3
  93. package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +2 -2
  94. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +4 -5
  95. package/src/runtime/agent/orchestrator/runtime-core/goal-tool-defs.mjs +2 -2
  96. package/src/runtime/agent/orchestrator/runtime-core/provider-request-tools.mjs +15 -8
  97. package/src/runtime/agent/orchestrator/runtime-core/session-title.mjs +1 -0
  98. package/src/runtime/agent/orchestrator/runtime-core/todo-list.mjs +9 -32
  99. package/src/runtime/agent/orchestrator/runtime-core/todo-tool-defs.mjs +4 -5
  100. package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +1 -3
  101. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +5 -2
  102. package/src/runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs +2 -17
  103. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +7 -3
  104. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +9 -2
  105. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +26 -13
  106. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +4 -5
  107. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +16 -5
  108. package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +22 -1
  109. package/src/runtime/agent/orchestrator/session/store/live-state.mjs +4 -0
  110. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +11 -9
  111. package/src/runtime/agent/orchestrator/tools/builtin/grep-formatting.mjs +2 -8
  112. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +1 -9
  113. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +2 -2
  114. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +1 -1
  115. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +12 -3
  116. package/src/runtime/agent/orchestrator/tools/code-graph/ast-calls.mjs +9 -2
  117. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +137 -7
  118. package/src/runtime/agent/orchestrator/tools/code-graph/calls-cache.mjs +43 -14
  119. package/src/runtime/agent/orchestrator/tools/code-graph/calls-sidecar-worker.mjs +33 -0
  120. package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +146 -11
  121. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +31 -24
  122. package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary/spawn-jsonl.mjs +172 -25
  123. package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +100 -2
  124. package/src/runtime/agent/orchestrator/tools/code-graph/main-thread-slice.mjs +18 -0
  125. package/src/runtime/agent/orchestrator/tools/code-graph/mask-pool.mjs +219 -0
  126. package/src/runtime/agent/orchestrator/tools/code-graph/mask-worker.mjs +12 -0
  127. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +6 -1
  128. package/src/runtime/agent/orchestrator/tools/code-graph/modes/calls.mjs +9 -2
  129. package/src/runtime/agent/orchestrator/tools/code-graph/modes/dependents.mjs +5 -1
  130. package/src/runtime/agent/orchestrator/tools/code-graph/modes/structure.mjs +8 -2
  131. package/src/runtime/agent/orchestrator/tools/code-graph/modes/symbols.mjs +14 -11
  132. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +41 -18
  133. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +391 -83
  134. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +109 -9
  135. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +73 -29
  136. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +6 -5
  137. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +7 -3
  138. package/src/runtime/channels/lib/crash-log.mjs +21 -1
  139. package/src/runtime/channels/lib/worker-main.mjs +8 -25
  140. package/src/runtime/media/jobs.mjs +5 -0
  141. package/src/runtime/media/store.mjs +146 -3
  142. package/src/runtime/office/core/office-write-ledger.mjs +2 -2
  143. package/src/runtime/shared/agent-reap-state.mjs +19 -0
  144. package/src/runtime/shared/desktop-notice-host.d.mts +13 -0
  145. package/src/runtime/shared/desktop-notice-host.mjs +87 -0
  146. package/src/runtime/shared/file-lock.mjs +2 -2
  147. package/src/runtime/shared/heap-cap.mjs +9 -11
  148. package/src/runtime/shared/llm/http-agent.mjs +11 -1
  149. package/src/runtime/shared/llm/system-proxy.mjs +100 -25
  150. package/src/runtime/shared/llm/usage-accounting.mjs +18 -7
  151. package/src/runtime/shared/llm/usage-context.mjs +2 -2
  152. package/src/runtime/shared/llm/usage-ledger-requests.mjs +10 -3
  153. package/src/runtime/shared/llm/usage-ledger.mjs +13 -1
  154. package/src/runtime/shared/provider-accounts.mjs +22 -0
  155. package/src/runtime/shared/provider-auth-binding.mjs +2 -2
  156. package/src/runtime/shared/resource-admission.mjs +2 -2
  157. package/src/runtime/shared/root-async-context.mjs +51 -0
  158. package/src/runtime/shared/run-child.mjs +18 -1
  159. package/src/runtime/shared/slow-span.mjs +2 -2
  160. package/src/runtime/shared/tool-execution-owner.mjs +2 -2
  161. package/src/runtime/shared/tool-work-units.mjs +2 -0
  162. package/src/runtime/shared/turn-snapshot-store.mjs +75 -18
  163. package/src/runtime/shared/turn-worktree-snapshot.mjs +38 -8
  164. package/src/runtime/shared/user-cwd.mjs +2 -2
  165. package/src/runtime/shared/worker-requests.mjs +3 -1
  166. package/src/runtime/shared/worktrees/lock.mjs +2 -2
  167. package/src/runtime/visualize-bridge/client.mjs +26 -4
  168. package/src/runtime/visualize-bridge/tool-defs.mjs +46 -5
  169. package/src/session-runtime/boot/apis.mjs +1 -0
  170. package/src/session-runtime/boot/begin.mjs +2 -0
  171. package/src/session-runtime/media-api.mjs +15 -0
  172. package/src/session-runtime/provider-readiness.mjs +10 -2
  173. package/src/session-runtime/runtime-core.mjs +35 -8
  174. package/src/session-runtime/runtime-review-api.mjs +3 -1
  175. package/src/session-runtime/services/agent-tool/close-flow.mjs +6 -1
  176. package/src/session-runtime/services/agent-tool/execute-resume.mjs +94 -0
  177. package/src/session-runtime/services/agent-tool/execute-send.mjs +77 -27
  178. package/src/session-runtime/services/agent-tool/execute-spawn.mjs +28 -7
  179. package/src/session-runtime/services/agent-tool/execute.mjs +6 -1
  180. package/src/session-runtime/services/agent-tool/helpers.mjs +11 -0
  181. package/src/session-runtime/services/agent-tool/job-views/job-render.mjs +13 -10
  182. package/src/session-runtime/services/agent-tool/render.mjs +2 -0
  183. package/src/session-runtime/services/agent-tool/send-flow.mjs +1 -0
  184. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -0
  185. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +2 -1
  186. package/src/session-runtime/services/agent-tool/tag-registry/reaped-sessions.mjs +82 -0
  187. package/src/session-runtime/services/agent-tool/tag-registry/record-facts-worker.mjs +36 -0
  188. package/src/session-runtime/services/agent-tool/tag-registry.mjs +4 -0
  189. package/src/session-runtime/services/agent-tool/terminal-reaper/row-helpers.mjs +29 -0
  190. package/src/session-runtime/services/agent-tool/terminal-reaper/scan-admission.mjs +11 -3
  191. package/src/session-runtime/services/agent-tool/terminal-reaper/stale-rows.mjs +19 -8
  192. package/src/session-runtime/services/agent-tool/terminal-reaper.mjs +5 -2
  193. package/src/session-runtime/services/agent-tool/worker-index.mjs +1 -0
  194. package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +2 -2
  195. package/src/session-runtime/session-create.mjs +5 -0
  196. package/src/session-runtime/setup-tool/settings-contract.mjs +2 -0
  197. package/src/session-runtime/usage-stats-api.mjs +3 -0
  198. package/src/session-runtime/workspace/admission-gate.mjs +25 -7
  199. package/src/session-runtime/workspace/transitions.mjs +4 -0
  200. package/src/standalone/daemon-log.mjs +28 -4
  201. package/src/standalone/daemon-owner.mjs +41 -7
  202. package/src/standalone/daemon-work-gate.mjs +139 -0
  203. package/src/standalone/daemon.mjs +80 -11
  204. package/src/standalone/desktop-service-registry.mjs +11 -4
  205. package/src/standalone/session-client.mjs +57 -5
  206. package/src/standalone/session-protocol.mjs +5 -0
  207. package/src/standalone/session-service/agent-tree/agent-cancel.mjs +17 -1
  208. package/src/standalone/session-service/agent-tree.mjs +7 -0
  209. package/src/standalone/session-service/session-calls/session-turns.mjs +12 -5
  210. package/src/standalone/session-transport/call-route.mjs +10 -4
  211. package/src/standalone/session-transport/routes.mjs +21 -0
  212. package/src/standalone/session-transport/stack.mjs +3 -1
  213. package/src/standalone/session-transport.mjs +5 -0
  214. package/src/tui/dist/index.mjs +495 -477
  215. package/src/tui/session/session-api/media.mjs +5 -0
  216. package/src/tui/session/turn.mjs +13 -0
  217. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/cancellation.mjs +0 -71
  218. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/reader.mjs +0 -108
@@ -11,13 +11,14 @@
11
11
  import { geminiThinkingConfig } from './gemini-thinking.mjs';
12
12
  import { geminiMaxOutputTokens } from './gemini-output-limit.mjs';
13
13
  import { toGeminiContents, toGeminiRequestTools, toGeminiToolConfig } from './gemini-schema.mjs';
14
+ import { geminiIgnoresSamplingParams } from './gemini-model-redirect.mjs';
14
15
 
15
- // Request pieces shared by the cached REST path and the SDK path.
16
+ // Request pieces shared by the cached and uncached REST bodies.
16
17
  // Caller-supplied generation controls the wire carries in generationConfig.
17
18
  // maxOutputTokens counts thought tokens too (see the thinking docs). Anything
18
19
  // invalid is rejected here instead of being dropped. (safetySettings is a
19
20
  // request-level field, forwarded separately.)
20
- function geminiGenerationControls(opts, useModel, outputLimit) {
21
+ function geminiGenerationControls(opts, useModel, outputLimit, omitIgnoredSampling) {
21
22
  const controls = {};
22
23
  const maxOutputTokens = geminiMaxOutputTokens(useModel, opts, outputLimit);
23
24
  if (maxOutputTokens !== undefined) controls.maxOutputTokens = maxOutputTokens;
@@ -26,20 +27,29 @@ function geminiGenerationControls(opts, useModel, outputLimit) {
26
27
  if (!Number.isFinite(temperature) || temperature < 0 || temperature > 2) {
27
28
  throw new TypeError('temperature must be a number between 0 and 2.');
28
29
  }
29
- controls.temperature = temperature;
30
+ if (!(omitIgnoredSampling && geminiIgnoresSamplingParams(useModel))) controls.temperature = temperature;
30
31
  }
31
32
  return controls;
32
33
  }
33
34
 
34
35
  // `outputLimit` is the provider roster's declared output limit for the model.
35
- export function buildGeminiRequest(messages, useModel, tools, opts, outputLimit = null) {
36
+ // `omitIgnoredSampling` drops temperature for models the Gemini API documents
37
+ // as ignoring it (the Gemini API-key route; other routes keep their wire).
38
+ export function buildGeminiRequest(
39
+ messages,
40
+ useModel,
41
+ tools,
42
+ opts,
43
+ outputLimit = null,
44
+ { omitIgnoredSampling = false } = {}
45
+ ) {
36
46
  // Gemini returns thought summaries only when the request asks for them.
37
47
  // Without this the reasoning channel stays empty for the whole turn and
38
48
  // the model's only visible output is the plain pre-tool text, so every
39
49
  // round reads as another preamble. On by default for every model; an
40
50
  // explicit opts.includeThoughts still wins.
41
51
  const thinkingConfig = geminiThinkingConfig(useModel, opts, { includeThoughts: true });
42
- const controls = geminiGenerationControls(opts, useModel, outputLimit);
52
+ const controls = geminiGenerationControls(opts, useModel, outputLimit, omitIgnoredSampling);
43
53
  let generationConfig;
44
54
  if (thinkingConfig || Object.keys(controls).length) {
45
55
  generationConfig = { ...(thinkingConfig ? { thinkingConfig } : {}), ...controls };
@@ -66,6 +76,25 @@ export function buildGeminiRequest(messages, useModel, tools, opts, outputLimit
66
76
  return { generationConfig, systemInstruction, contents, geminiTools, toolConfig, safetySettings };
67
77
  }
68
78
 
79
+ // The generateContent body without a cached prefix: the whole request.
80
+ export function geminiUncachedRestBody({
81
+ contents,
82
+ systemInstruction,
83
+ geminiTools,
84
+ toolConfig,
85
+ generationConfig,
86
+ safetySettings,
87
+ }) {
88
+ return {
89
+ contents,
90
+ ...(systemInstruction ? { systemInstruction: { role: 'system', parts: [{ text: systemInstruction }] } } : {}),
91
+ ...(geminiTools ? { tools: geminiTools } : {}),
92
+ ...(toolConfig ? { toolConfig } : {}),
93
+ ...(generationConfig ? { generationConfig } : {}),
94
+ ...(safetySettings ? { safetySettings } : {}),
95
+ };
96
+ }
97
+
69
98
  // The generateContent body for a cached prefix. The cache carries the
70
99
  // recorded prefix; every uncached tail turn is sent, not just the last
71
100
  // message, so reused cachedContents preserve full conversation context
@@ -104,6 +104,16 @@ export function normalizeGeminiUsage(um, opts, cachedContent) {
104
104
  // subset). Alias the resolver's normalized total directly.
105
105
  promptTokens: inputTokens,
106
106
  };
107
+ // A long-decode turn bills every hop's prompt, but the context only holds
108
+ // the first hop's prompt plus what was generated. The summed input stays the
109
+ // billing figure; this is the input the context gauge and compaction count.
110
+ const initialPromptTokens = Number(um.initialPromptTokenCount);
111
+ if (initialPromptTokens > 0 && initialPromptTokens < inputTokens) {
112
+ resolvedUsage.contextInputTokens = initialPromptTokens;
113
+ // The cached reads of the billed hops repeat the same way; the context
114
+ // holds only the first hop's.
115
+ resolvedUsage.contextCachedTokens = Math.min(Number(um.initialCachedContentTokenCount) || 0, initialPromptTokens);
116
+ }
107
117
  return { resolvedUsage, cache };
108
118
  }
109
119
 
@@ -3,7 +3,15 @@
3
3
  * FunctionDeclarationSchema, tool/tool-config mapping, message → content
4
4
  * mapping, tool-call parsing/emission, and grounding-source collection.
5
5
  */
6
- import { SchemaType } from '@google/generative-ai';
6
+ // The Gemini Schema `type` values, as the v1beta wire spells them.
7
+ const SchemaType = Object.freeze({
8
+ STRING: 'string',
9
+ NUMBER: 'number',
10
+ INTEGER: 'integer',
11
+ BOOLEAN: 'boolean',
12
+ ARRAY: 'array',
13
+ OBJECT: 'object',
14
+ });
7
15
  import { traceHash, stableTraceStringify } from './trace-utils.mjs';
8
16
  import {
9
17
  normalizeContentForGeminiParts,
@@ -89,7 +97,6 @@ function splitGeminiToolContent(content) {
89
97
 
90
98
  /**
91
99
  * Convert JSON Schema type string to Gemini SchemaType.
92
- * Gemini SDK uses its own enum instead of plain strings.
93
100
  */
94
101
  function toSchemaType(t) {
95
102
  const map = {
@@ -1107,10 +1114,8 @@ export function parseGeminiTextPartMetadata(parts) {
1107
1114
  export function parseToolCalls(parts) {
1108
1115
  const calls = parts.filter((p) => 'functionCall' in p && !!p.functionCall);
1109
1116
  if (!calls.length) return undefined;
1110
- // The @google/generative-ai 0.24.1 SDK predates Gemini 3 thinking — its
1111
- // FunctionCall type only declares { name, args }. The runtime object,
1112
- // however, retains whatever the wire response carried, which means the
1113
- // signature may sit under any of:
1117
+ // A FunctionCall part retains whatever the wire response carried, which
1118
+ // means the signature may sit under any of:
1114
1119
  // • part.functionCall.thoughtSignature (camelCase, expected)
1115
1120
  // • part.functionCall.thought_signature (snake_case, raw protobuf)
1116
1121
  // • part.thoughtSignature / part.thought_signature (sibling on Part)
@@ -1,18 +1,9 @@
1
1
  /**
2
- * One SDK (`@google/generative-ai`) streaming attempt and the request
3
- * controller lifetime around it: the parent-abort link that lives for the
4
- * FULL stream, the connect-phase first-byte timer that is dropped once bytes
5
- * arrive, and the text-leak guard both transports build from the same turn
6
- * inputs. Frame consumption itself stays in gemini-stream.mjs.
2
+ * The text-leak guard every Gemini-shaped REST transport builds from the same
3
+ * turn inputs. (The module name predates the removal of the legacy SDK; the
4
+ * Vertex and OpenCode Go engines import the guard from here.)
7
5
  */
8
- import {
9
- GEMINI_FIRST_BYTE_TIMEOUT_MS,
10
- geminiTimeoutError,
11
- createGeminiTextLeakGuard,
12
- consumeGeminiSdkStream,
13
- normalizeGeminiSdkError,
14
- } from './gemini-stream.mjs';
15
- import { geminiFailureUsage } from './gemini-response.mjs';
6
+ import { createGeminiTextLeakGuard } from './gemini-stream.mjs';
16
7
 
17
8
  export function geminiTextLeakGuardFor({ tools, callbacks }) {
18
9
  return createGeminiTextLeakGuard({
@@ -23,90 +14,3 @@ export function geminiTextLeakGuardFor({ tools, callbacks }) {
23
14
  deferToolCalls: true,
24
15
  });
25
16
  }
26
-
27
- // Mirrors the REST branch's signal lifetime: the request controller stays
28
- // linked to the parent (attemptSignal) for the FULL stream — connect AND
29
- // body — so a parent / client / gateway abort after first byte still
30
- // cancels the underlying SDK request (the SSE idle watchdog is off by
31
- // default). The first-byte timer only bounds the connect phase and is
32
- // cleared once the stream starts, so it can never kill a live,
33
- // still-producing stream.
34
- function linkSdkRequestController(attemptSignal) {
35
- const controller = new AbortController();
36
- let parentAbortListener = null;
37
- let firstByteTimer = null;
38
- const detachParent = () => {
39
- if (parentAbortListener && attemptSignal) {
40
- try {
41
- attemptSignal.removeEventListener('abort', parentAbortListener);
42
- } catch {}
43
- parentAbortListener = null;
44
- }
45
- };
46
- const clearConnectTimer = () => {
47
- if (firstByteTimer) {
48
- clearTimeout(firstByteTimer);
49
- firstByteTimer = null;
50
- }
51
- };
52
- if (attemptSignal) {
53
- if (attemptSignal.aborted) {
54
- try {
55
- controller.abort(attemptSignal.reason);
56
- } catch {}
57
- } else {
58
- parentAbortListener = () => {
59
- try {
60
- controller.abort(attemptSignal.reason);
61
- } catch {}
62
- };
63
- attemptSignal.addEventListener('abort', parentAbortListener, { once: true });
64
- }
65
- }
66
- firstByteTimer = setTimeout(() => {
67
- try {
68
- controller.abort(geminiTimeoutError('Gemini SDK first byte', GEMINI_FIRST_BYTE_TIMEOUT_MS));
69
- } catch {}
70
- }, GEMINI_FIRST_BYTE_TIMEOUT_MS);
71
- if (firstByteTimer.unref) firstByteTimer.unref();
72
- return { controller, detachParent, clearConnectTimer };
73
- }
74
-
75
- export async function streamGeminiSdkAttempt(genModel, stream, attemptSignal, onConnected = null) {
76
- const { contents, callbacks } = stream;
77
- const link = linkSdkRequestController(attemptSignal);
78
- const { controller } = link;
79
- try {
80
- let streamResult;
81
- try {
82
- streamResult = await genModel.generateContentStream({ contents }, { signal: controller.signal });
83
- } catch (err) {
84
- if (controller.signal.aborted) {
85
- throw controller.signal.reason instanceof Error ? controller.signal.reason : err;
86
- }
87
- throw normalizeGeminiSdkError(err, 'Gemini SDK streamGenerateContent');
88
- }
89
- // First byte / headers received: drop the connect-phase timer but KEEP
90
- // the parent link attached so a later abort during streaming still
91
- // reaches the request.
92
- link.clearConnectTimer();
93
- onConnected?.();
94
- const textLeakGuard = geminiTextLeakGuardFor(stream);
95
- const response = await consumeGeminiSdkStream(streamResult, {
96
- signal: attemptSignal,
97
- onStreamDelta: callbacks.onStreamDelta,
98
- onTextDelta: callbacks.onTextDelta,
99
- onReasoningDelta: callbacks.onReasoningDelta,
100
- textLeakGuard,
101
- label: 'Gemini SDK streamGenerateContent',
102
- failureUsage: geminiFailureUsage(stream.opts, stream.cachedContent, stream.useModel),
103
- cancelGeneration: (reason) => {
104
- if (!controller.signal.aborted) controller.abort(reason);
105
- },
106
- });
107
- return { response, textLeakGuard };
108
- } finally {
109
- link.clearConnectTimer();
110
- link.detachParent();
111
- }
112
- }
@@ -1,15 +1,10 @@
1
1
  /**
2
- * gemini-stream.mjs — Gemini stream consumption (REST + SDK) and stream guards.
2
+ * gemini-stream.mjs — Gemini REST stream consumption and stream guards.
3
3
  *
4
4
  * Owns chunk aggregation, completion assertions,
5
5
  * timeout/truncation error shapes and the text leak guard that recovers
6
6
  * tool calls emitted as plain text.
7
7
  */
8
- import {
9
- GoogleGenerativeAIAbortError,
10
- GoogleGenerativeAIError,
11
- GoogleGenerativeAIFetchError,
12
- } from '@google/generative-ai';
13
8
  import {
14
9
  PROVIDER_FIRST_BYTE_TIMEOUT_MS,
15
10
  PROVIDER_MAX_BEFORE_WARN_MS,
@@ -21,16 +16,10 @@ import { traceHash, stableTraceStringify } from './trace-utils.mjs';
21
16
  import { parseGeminiTextPartMetadata } from './gemini-schema.mjs';
22
17
  import { parseProviderJsonBatch } from './stream-json-pool.mjs';
23
18
  import { runAbortable } from '../../../shared/abort-race.mjs';
24
- import { createSdkStreamCancellation } from './gemini-sdk-stream/cancellation.mjs';
25
- import { createSdkStreamReader } from './gemini-sdk-stream/reader.mjs';
26
19
  import { createRestStreamWatchdogs } from './gemini-rest-stream/watchdogs.mjs';
27
20
  import { drainSseDataLines, sseDataPayload } from './gemini-rest-stream/sse-lines.mjs';
28
21
  import { noteAbandonedUsage } from '../../../shared/llm/usage-context.mjs';
29
- import {
30
- applyGeminiErrorContract,
31
- assertNoGeminiInBandError,
32
- geminiFinishReasonKind,
33
- } from './gemini-error-contract.mjs';
22
+ import { assertNoGeminiInBandError, geminiFinishReasonKind } from './gemini-error-contract.mjs';
34
23
 
35
24
  export const GEMINI_FIRST_BYTE_TIMEOUT_MS = resolveTimeoutMs(
36
25
  'MIXDOG_GEMINI_FIRST_BYTE_TIMEOUT_MS',
@@ -45,24 +34,6 @@ export function geminiTimeoutError(label, timeoutMs) {
45
34
  return err;
46
35
  }
47
36
 
48
- const GEMINI_RPC_CODES = new Set(['UNAVAILABLE', 'DEADLINE_EXCEEDED', 'ABORTED', 'INTERNAL', 'RESOURCE_EXHAUSTED']);
49
-
50
- /**
51
- * Copy a typed Gemini/gRPC status onto the error so classifyError can retry
52
- * UNAVAILABLE/DEADLINE_EXCEEDED/ABORTED/INTERNAL without an HTTP status.
53
- */
54
- function stampGeminiRpcError(err) {
55
- if (!err || typeof err !== 'object') return err;
56
- if (typeof err.geminiStatus === 'string' && err.geminiStatus) return err;
57
- for (const field of [err.status, err.error?.status, err.cause?.status, err.cause?.geminiStatus]) {
58
- if (typeof field === 'string' && GEMINI_RPC_CODES.has(field.toUpperCase())) {
59
- err.geminiStatus = field.toUpperCase();
60
- return err;
61
- }
62
- }
63
- return err;
64
- }
65
-
66
37
  function geminiTruncatedStreamError(message) {
67
38
  return Object.assign(new Error(message), {
68
39
  name: 'TruncatedStreamError',
@@ -80,75 +51,6 @@ function geminiStreamCorruptionError(message, cause = null) {
80
51
  });
81
52
  }
82
53
 
83
- // The SDK's own base error class. Its subclasses for an HTTP status
84
- // (FetchError) and a cancellation (AbortError) carry typed evidence of their
85
- // own; the bare class is what the SDK throws for everything else, and it sets
86
- // no `name` of its own.
87
- function isBareGoogleSdkError(err) {
88
- return (
89
- err instanceof GoogleGenerativeAIError &&
90
- !(err instanceof GoogleGenerativeAIFetchError) &&
91
- !(err instanceof GoogleGenerativeAIAbortError)
92
- );
93
- }
94
-
95
- function isGeminiSdkStreamParseError(err) {
96
- let cursor = err;
97
- const seen = new Set();
98
- for (let depth = 0; cursor && depth < 5 && !seen.has(cursor); depth++) {
99
- seen.add(cursor);
100
- if (cursor instanceof SyntaxError) return true;
101
- const message = String(cursor?.message || '');
102
- if (
103
- isBareGoogleSdkError(cursor) &&
104
- /(?:parse|parsing|json|unexpected token|unexpected end|unterminated)/i.test(message)
105
- ) {
106
- return true;
107
- }
108
- cursor = cursor?.cause;
109
- }
110
- return false;
111
- }
112
-
113
- // The SDK rethrows a network failure as a bare GoogleGenerativeAIError and
114
- // discards the socket error with its errno, so the SDK's own fixed wording is
115
- // the only evidence left. A failed body read is a stream cut short; a failed
116
- // request keeps the runtime's own message (e.g. 'fetch failed') after the URL,
117
- // which the shared transport rules already classify.
118
- const SDK_STREAM_READ_FAILURE = '[GoogleGenerativeAI Error]: Error reading from the stream';
119
- const SDK_FETCH_FAILURE_RE = /^\[GoogleGenerativeAI Error\]: Error fetching from \S+: ([\s\S]+)$/;
120
-
121
- function geminiSdkTransportError(err, label) {
122
- if (!isBareGoogleSdkError(err)) return null;
123
- if (err.message === SDK_STREAM_READ_FAILURE) {
124
- return Object.assign(new Error(`${label} stream read failed`, { cause: err }), {
125
- name: 'TruncatedStreamError',
126
- code: 'TRUNCATED_STREAM',
127
- truncatedStream: true,
128
- });
129
- }
130
- const fetchFailure = SDK_FETCH_FAILURE_RE.exec(err.message);
131
- if (!fetchFailure) return null;
132
- return Object.assign(new Error(fetchFailure[1].trim(), { cause: err }), { name: 'GeminiSdkFetchError' });
133
- }
134
-
135
- /** Typed shape of any SDK failure: transport loss, corrupt stream JSON, or an RPC status. */
136
- export function normalizeGeminiSdkError(err, label) {
137
- const transport = geminiSdkTransportError(err, label);
138
- if (transport) return transport;
139
- const stamped = stampGeminiRpcError(err);
140
- if (isGeminiSdkStreamParseError(stamped)) {
141
- return geminiStreamCorruptionError(`${label} corrupt SDK SSE JSON`, stamped);
142
- }
143
- if (!stamped || typeof stamped !== 'object') return stamped;
144
- return applyGeminiErrorContract(stamped, {
145
- details: stamped.details,
146
- errorDetails: stamped.errorDetails,
147
- googleStatus: stamped.geminiStatus,
148
- message: stamped.message,
149
- });
150
- }
151
-
152
54
  // CC-rule safety stamp for Gemini stream failures (provider-stall audit):
153
55
  // once text has actually been RELAYED to the live gateway or a leaked tool
154
56
  // call was dispatched, replaying would double-render/double-execute — the
@@ -365,7 +267,7 @@ function isCompleteFunctionCallPart(part) {
365
267
 
366
268
  // Concatenate the text parts of a single streamed Gemini chunk. Used to feed
367
269
  // the gateway live-text relay (onTextDelta) with the incremental text payload
368
- // as each SSE/SDK chunk arrives. Returns '' for tool-call / thought-only /
270
+ // as each SSE chunk arrives. Returns '' for tool-call / thought-only /
369
271
  // malformed chunks so the caller can skip empty emits.
370
272
  function geminiChunkText(chunk) {
371
273
  const parts = chunk?.candidates?.[0]?.content?.parts;
@@ -739,129 +641,3 @@ export async function consumeGeminiRestStreamResponse(
739
641
  }
740
642
  return aggregated;
741
643
  }
742
-
743
- export async function consumeGeminiSdkStream(
744
- streamResult,
745
- {
746
- signal,
747
- onStreamDelta,
748
- onTextDelta,
749
- onReasoningDelta = null,
750
- textLeakGuard,
751
- label,
752
- cancelGeneration,
753
- firstByteTimeoutMs = GEMINI_FIRST_BYTE_TIMEOUT_MS,
754
- cancellationGraceMs = 250,
755
- failureUsage = null,
756
- }
757
- ) {
758
- let relayedText = '';
759
- const finalizeLeakGuard = createLeakGuardFinalizer(textLeakGuard);
760
-
761
- const cancellation = createSdkStreamCancellation({ signal, label, cancelGeneration, cancellationGraceMs });
762
- const { abortError } = cancellation;
763
- let reader = null;
764
- const onSignalAbort = () => {
765
- const err = abortError();
766
- reader?.rejectPending(err);
767
- cancellation.cancelInFlight(err).catch(() => {});
768
- };
769
- const collectedChunks = [];
770
-
771
- try {
772
- // Observe the SDK's aggregate branch even when cancellation precedes
773
- // consumption: aborting the acquired request can reject both branches.
774
- let responsePromise;
775
- try {
776
- responsePromise = Promise.resolve(streamResult.response);
777
- } catch (err) {
778
- responsePromise = Promise.reject(err);
779
- }
780
- responsePromise.catch(() => {});
781
- const iterator = streamResult.stream[Symbol.asyncIterator]();
782
- cancellation.bindIterator(iterator);
783
- reader = createSdkStreamReader({
784
- iterator,
785
- label,
786
- firstByteTimeoutMs,
787
- timeoutError: geminiTimeoutError,
788
- cancellation,
789
- });
790
- if (signal?.aborted) throw abortError();
791
- signal?.addEventListener('abort', onSignalAbort, { once: true });
792
- reader.arm();
793
- while (true) {
794
- if (signal?.aborted) throw abortError();
795
- if (reader.idleTimedOut) throw reader.idleError();
796
- let step;
797
- try {
798
- step = await reader.next();
799
- } catch (err) {
800
- if (reader.idleTimedOut) throw reader.idleError();
801
- if (signal?.aborted) throw abortError();
802
- throw normalizeGeminiSdkError(err, label);
803
- }
804
- if (signal?.aborted) throw abortError();
805
- if (step.done) break;
806
- reader.noteChunk();
807
- assertNoGeminiInBandError(step.value, label);
808
- if (step.value) collectedChunks.push(step.value);
809
- try {
810
- onStreamDelta?.(geminiChunkProgressKind(step.value));
811
- } catch {}
812
- relayGeminiReasoning(step.value, onReasoningDelta);
813
- if (onTextDelta || textLeakGuard) {
814
- const t = geminiChunkText(step.value);
815
- relayedText += relayGeminiStreamText(t, { onTextDelta, textLeakGuard });
816
- }
817
- }
818
- if (reader.idleTimedOut) throw reader.idleError();
819
- reader.stop();
820
-
821
- // SDK 0.24.1 aggregation drops thoughtSignature. Preserve wire parts
822
- // locally; retain the SDK response path only for an empty collection.
823
- let raw;
824
- if (collectedChunks.length > 0) {
825
- raw = aggregateGeminiStreamChunks(collectedChunks, label);
826
- } else {
827
- let response;
828
- try {
829
- response = await runAbortable(signal, () => responsePromise);
830
- } catch (err) {
831
- throw normalizeGeminiSdkError(err, label);
832
- }
833
- raw = response?.candidates ? response : response?.response || response;
834
- assertNoGeminiInBandError(raw, label);
835
- }
836
- const finishReason = raw?.candidates?.[0]?.finishReason || null;
837
- const promptBlockReason = raw?.promptFeedback?.blockReason || null;
838
- assertGeminiStreamCompleted({
839
- sawStreamChunk: reader.sawStreamChunk,
840
- finishReason,
841
- promptBlockReason,
842
- parts: raw?.candidates?.[0]?.content?.parts,
843
- label,
844
- });
845
- return raw;
846
- } catch (err) {
847
- reader?.clearFirstByte();
848
- const failure = signal?.aborted ? abortError() : err;
849
- await cancellation.cancelInFlight(failure);
850
- finalizeLeakGuard();
851
- throw stampGeminiStreamFailure(failure, {
852
- relayedText,
853
- textLeakGuard,
854
- chunks: collectedChunks,
855
- failureUsage,
856
- cancelled: signal?.aborted === true,
857
- });
858
- } finally {
859
- reader?.stop();
860
- if (signal) {
861
- try {
862
- signal.removeEventListener('abort', onSignalAbort);
863
- } catch {}
864
- }
865
- finalizeLeakGuard();
866
- }
867
- }