@swarmclawai/swarmclaw 1.9.28 → 1.9.29

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.
package/README.md CHANGED
@@ -151,15 +151,14 @@ clawhub install swarmclaw
151
151
 
152
152
  [Browse on ClawHub](https://clawhub.ai/skills/swarmclaw)
153
153
 
154
- ## v1.9.28 Highlights
154
+ ## v1.9.29 Highlights
155
155
 
156
- Issue-fix release for installed CLI groups, email bridge TLS handling, built-in model overrides, and Windows desktop native modules.
156
+ Issue-fix release for Edit Agent tooltips, installed package builds, and structured dream output on local Ollama models.
157
157
 
158
- - **Installed CLI groups.** Global npm installs route legacy API-backed group commands through the bundled TS runtime when installed under `node_modules`, avoiding Node 22.6+/25 type-stripping failures.
159
- - **Email bridge TLS resilience.** The email connector logs IMAP socket errors without crashing the daemon and supports `tlsRejectUnauthorized=false` for local self-signed IMAP/SMTP servers.
160
- - **Provider model override persistence.** Built-in provider live model saves now reload array-valued overrides instead of falling back to catalog defaults.
161
- - **Windows desktop native modules.** Desktop packaging syncs rebuilt Electron-native modules into traced `.next/node_modules` aliases so packaged Windows installs start against the correct ABI.
162
- - **Regression coverage.** CLI, email, provider route, and Electron after-pack tests cover the reported failure modes.
158
+ - **Edit Agent tooltips.** Help tips in the Edit Agent sheet now render above modal layers instead of being hidden behind the dialog.
159
+ - **Installed package builds.** The npm package now ships the Dagre type declarations needed by `swarmclaw server --build`.
160
+ - **Local Ollama dream output.** Structured dream/reflection calls request Ollama JSON mode and validate balanced JSON before writing memories.
161
+ - **Regression coverage.** CLI/package, model-build, and dream-parser tests cover the reported failure modes.
163
162
 
164
163
  ## Hosted Deploys
165
164
 
@@ -411,6 +410,15 @@ Operational docs: https://swarmclaw.ai/docs/observability
411
410
 
412
411
  ## Releases
413
412
 
413
+ ### v1.9.29 Highlights
414
+
415
+ Issue-fix release for Edit Agent tooltips, installed package builds, and structured dream output on local Ollama models.
416
+
417
+ - **Edit Agent tooltips.** Help tips in the Edit Agent sheet now render above modal layers instead of being hidden behind the dialog.
418
+ - **Installed package builds.** The npm package now ships the Dagre type declarations needed by `swarmclaw server --build`.
419
+ - **Local Ollama dream output.** Structured dream/reflection calls request Ollama JSON mode and validate balanced JSON before writing memories.
420
+ - **Regression coverage.** CLI/package, model-build, and dream-parser tests cover the reported failure modes.
421
+
414
422
  ### v1.9.28 Highlights
415
423
 
416
424
  Issue-fix release for installed CLI groups, email bridge TLS handling, built-in model overrides, and Windows desktop native modules.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swarmclawai/swarmclaw",
3
- "version": "1.9.28",
3
+ "version": "1.9.29",
4
4
  "description": "Build and run autonomous AI agents with OpenClaw, Hermes, multiple model providers, orchestration, delegation, memory, skills, schedules, and chat connectors.",
5
5
  "main": "electron-dist/main.js",
6
6
  "license": "MIT",
@@ -88,7 +88,7 @@
88
88
  "test:cli": "node --test src/cli/*.test.js bin/*.test.js scripts/electron-after-pack.test.mjs scripts/electron-signing-config.test.mjs scripts/ensure-sandbox-browser-image.test.mjs scripts/postinstall.test.mjs scripts/run-next-build.test.mjs scripts/run-next-typegen.test.mjs",
89
89
  "test:setup": "tsx --test src/app/api/setup/check-provider/route.test.ts src/lib/server/provider-model-discovery.test.ts src/components/auth/setup-wizard/utils.test.ts src/components/auth/setup-wizard/types.test.ts src/hooks/setup-done-detection.test.ts src/lib/setup-defaults.test.ts src/lib/server/storage-auth.test.ts src/lib/server/storage-auth-docker.test.ts",
90
90
  "test:openclaw": "tsx --test src/lib/openclaw/openclaw-agent-id.test.ts src/lib/openclaw/openclaw-endpoint.test.ts src/lib/server/agents/agent-runtime-config.test.ts src/lib/server/build-llm.test.ts src/lib/server/connectors/connector-routing.test.ts src/lib/server/connectors/openclaw.test.ts src/lib/server/connectors/swarmdock.test.ts src/lib/server/gateway/protocol.test.ts src/lib/server/gateways/gateway-topology.test.ts src/lib/server/llm-response-cache.test.ts src/lib/server/mcp-conformance.test.ts src/lib/server/openclaw/agent-resolver.test.ts src/lib/server/openclaw/deploy.test.ts src/lib/server/openclaw/skills-normalize.test.ts src/lib/server/session-tools/openclaw-nodes.test.ts src/lib/server/session-tools/swarmdock.test.ts src/lib/server/tasks/task-quality-gate.test.ts src/lib/server/tasks/task-validation.test.ts src/lib/server/tool-capability-policy.test.ts src/lib/providers/openai.test.ts src/lib/providers/openclaw-exports.test.ts src/app/api/gateways/topology-route.test.ts src/app/api/openclaw/dashboard-url/route.test.ts",
91
- "test:runtime": "tsx --test src/lib/a2a/agent-card.test.ts src/lib/agent-planning-mode.test.ts src/lib/agent-config-history.test.ts src/lib/strip-internal-metadata.test.ts src/lib/provider-sets.test.ts src/lib/providers/opencode-cli.test.ts src/lib/providers/cli-provider-metadata.test.ts src/lib/providers/cli-utils.test.ts src/lib/providers/generic-cli.test.ts src/lib/server/agents/delegation-advisory.test.ts src/lib/server/agents/agent-runtime-config.test.ts src/lib/server/cli-provider-readiness.test.ts src/lib/server/provider-health.test.ts src/lib/server/provider-diagnostics.test.ts src/lib/server/mcp-gateway-runtime.test.ts src/lib/server/mcp-connection-pool.test.ts src/lib/server/knowledge-sources.test.ts src/lib/server/extension-managed-resources.test.ts src/lib/server/eval/baseline.test.ts src/lib/server/eval/environment-plan.test.ts src/lib/server/chat-execution/chat-execution-grounding.test.ts src/lib/server/chat-execution/chat-turn-preparation.test.ts src/lib/server/chat-execution/iteration-timers.test.ts src/lib/server/chat-execution/post-stream-finalization.test.ts src/lib/server/chat-execution/prompt-sections.planning-mode.test.ts src/lib/server/chat-execution/reasoning-tag-scrubber.test.ts src/lib/server/chats/clear-undo-snapshots.test.ts src/lib/server/chats/session-context-pack.test.ts src/lib/server/connectors/email.test.ts src/lib/server/connectors/slack.test.ts src/lib/server/protocols/protocol-service.test.ts src/lib/server/runtime/run-ledger.test.ts src/lib/server/runtime/queue-retry-policy.test.ts src/lib/server/runs/run-brief.test.ts src/lib/server/runs/run-handoff.test.ts src/lib/server/operations/operation-pulse.test.ts src/lib/server/schedules/schedule-history.test.ts src/lib/server/schedules/schedule-timing.test.ts src/lib/server/schedules/schedule-preview.test.ts src/lib/quality/release-readiness.test.ts src/lib/quality/architecture-health.test.ts src/lib/server/artifacts/artifact-resolver.test.ts src/lib/server/observability/otel-config.test.ts src/lib/server/safe-parse-body.test.ts src/lib/server/missions/mission-templates.test.ts src/lib/server/sharing/share-link-repository.test.ts src/lib/server/sharing/share-resolver.test.ts src/lib/server/tasks/task-execution-workspace.test.ts src/lib/server/tasks/task-execution-policy.test.ts src/lib/server/tasks/task-handoff.test.ts src/lib/server/tasks/task-service.test.ts src/lib/server/session-tools/execute.test.ts src/lib/server/session-tools/manage-tasks.test.ts src/lib/server/session-tools/web-crawl.test.ts src/lib/app/view-constants.test.ts src/lib/quality/quality-summary.test.ts src/app/api/approvals/route.test.ts src/app/api/agents/agents-route.test.ts src/app/api/tasks/tasks-route.test.ts src/app/api/tasks/task-workspace-route.test.ts src/app/api/chats/chat-route.test.ts src/app/api/chats/clear-route.test.ts src/app/api/chats/compact-route.test.ts src/app/api/chats/context-pack-route.test.ts src/app/api/chats/context-status-route.test.ts src/app/api/config-versions/config-versions-route.test.ts src/app/api/runs/run-handoff-route.test.ts src/app/api/connectors/connector-doctor-route.test.ts src/app/api/extensions/managed-resources/route.test.ts src/app/api/gateways/control-route.test.ts src/app/api/healthz/route.test.ts src/app/api/logs/route.test.ts src/app/api/portability/export/route.test.ts src/app/api/portability/import/route.test.ts src/app/api/providers/[id]/route.test.ts src/app/api/schedules/preview/route.test.ts src/app/api/schedules/schedule-history-route.test.ts src/app/api/tts/route.test.ts",
91
+ "test:runtime": "tsx --test src/lib/a2a/agent-card.test.ts src/lib/agent-planning-mode.test.ts src/lib/agent-config-history.test.ts src/lib/strip-internal-metadata.test.ts src/lib/provider-sets.test.ts src/lib/providers/opencode-cli.test.ts src/lib/providers/cli-provider-metadata.test.ts src/lib/providers/cli-utils.test.ts src/lib/providers/generic-cli.test.ts src/lib/server/agents/delegation-advisory.test.ts src/lib/server/agents/agent-runtime-config.test.ts src/lib/server/cli-provider-readiness.test.ts src/lib/server/provider-health.test.ts src/lib/server/provider-diagnostics.test.ts src/lib/server/mcp-gateway-runtime.test.ts src/lib/server/mcp-connection-pool.test.ts src/lib/server/knowledge-sources.test.ts src/lib/server/memory/dream-service.test.ts src/lib/server/extension-managed-resources.test.ts src/lib/server/eval/baseline.test.ts src/lib/server/eval/environment-plan.test.ts src/lib/server/chat-execution/chat-execution-grounding.test.ts src/lib/server/chat-execution/chat-turn-preparation.test.ts src/lib/server/chat-execution/iteration-timers.test.ts src/lib/server/chat-execution/post-stream-finalization.test.ts src/lib/server/chat-execution/prompt-sections.planning-mode.test.ts src/lib/server/chat-execution/reasoning-tag-scrubber.test.ts src/lib/server/chats/clear-undo-snapshots.test.ts src/lib/server/chats/session-context-pack.test.ts src/lib/server/connectors/email.test.ts src/lib/server/connectors/slack.test.ts src/lib/server/protocols/protocol-service.test.ts src/lib/server/runtime/run-ledger.test.ts src/lib/server/runtime/queue-retry-policy.test.ts src/lib/server/runs/run-brief.test.ts src/lib/server/runs/run-handoff.test.ts src/lib/server/operations/operation-pulse.test.ts src/lib/server/schedules/schedule-history.test.ts src/lib/server/schedules/schedule-timing.test.ts src/lib/server/schedules/schedule-preview.test.ts src/lib/quality/release-readiness.test.ts src/lib/quality/architecture-health.test.ts src/lib/server/artifacts/artifact-resolver.test.ts src/lib/server/observability/otel-config.test.ts src/lib/server/safe-parse-body.test.ts src/lib/server/missions/mission-templates.test.ts src/lib/server/sharing/share-link-repository.test.ts src/lib/server/sharing/share-resolver.test.ts src/lib/server/tasks/task-execution-workspace.test.ts src/lib/server/tasks/task-execution-policy.test.ts src/lib/server/tasks/task-handoff.test.ts src/lib/server/tasks/task-service.test.ts src/lib/server/session-tools/execute.test.ts src/lib/server/session-tools/manage-tasks.test.ts src/lib/server/session-tools/web-crawl.test.ts src/lib/app/view-constants.test.ts src/lib/quality/quality-summary.test.ts src/app/api/approvals/route.test.ts src/app/api/agents/agents-route.test.ts src/app/api/tasks/tasks-route.test.ts src/app/api/tasks/task-workspace-route.test.ts src/app/api/chats/chat-route.test.ts src/app/api/chats/clear-route.test.ts src/app/api/chats/compact-route.test.ts src/app/api/chats/context-pack-route.test.ts src/app/api/chats/context-status-route.test.ts src/app/api/config-versions/config-versions-route.test.ts src/app/api/runs/run-handoff-route.test.ts src/app/api/connectors/connector-doctor-route.test.ts src/app/api/extensions/managed-resources/route.test.ts src/app/api/gateways/control-route.test.ts src/app/api/healthz/route.test.ts src/app/api/logs/route.test.ts src/app/api/portability/export/route.test.ts src/app/api/portability/import/route.test.ts src/app/api/providers/[id]/route.test.ts src/app/api/schedules/preview/route.test.ts src/app/api/schedules/schedule-history-route.test.ts src/app/api/tts/route.test.ts",
92
92
  "test:builder": "tsx --test src/features/protocols/builder/utils/nodes-to-template.test.ts src/features/protocols/builder/utils/template-to-nodes.test.ts src/features/protocols/builder/validators/dag-validator.test.ts",
93
93
  "test:e2e": "node --import tsx scripts/browser-e2e-smoke.ts",
94
94
  "test:mcp:conformance": "node --import tsx ./scripts/mcp-conformance-check.ts",
@@ -119,6 +119,7 @@
119
119
  "@tailwindcss/postcss": "^4",
120
120
  "@tanstack/react-query": "^5.91.0",
121
121
  "@types/better-sqlite3": "^7.6.13",
122
+ "@types/dagre": "^0.7.54",
122
123
  "@types/mailparser": "^3.4.6",
123
124
  "@types/node": "^20",
124
125
  "@types/nodemailer": "^7.0.11",
@@ -179,7 +180,6 @@
179
180
  },
180
181
  "devDependencies": {
181
182
  "@electron/rebuild": "^3.7.2",
182
- "@types/dagre": "^0.7.54",
183
183
  "electron": "^33.3.0",
184
184
  "electron-builder": "^25.1.8",
185
185
  "eslint": "^9",
@@ -199,6 +199,12 @@ test('binary -v alias output matches package version', () => {
199
199
  assert.equal(result.stdout.trim(), `${PACKAGE_JSON.name} ${PACKAGE_JSON.version}`)
200
200
  })
201
201
 
202
+ test('package ships dagre type declarations required by installed builds', () => {
203
+ assert.equal(PACKAGE_JSON.dependencies.dagre, '^0.8.5')
204
+ assert.equal(PACKAGE_JSON.dependencies['@types/dagre'], '^0.7.54')
205
+ assert.equal(PACKAGE_JSON.devDependencies?.['@types/dagre'], undefined)
206
+ })
207
+
202
208
  test('legacy TS launcher falls back to tsx import when strip-types is unavailable', () => {
203
209
  const cliPath = path.join(APP_ROOT, 'src', 'cli', 'index.ts')
204
210
  const args = buildLegacyTsCliArgs(cliPath, ['runs', 'list'], {
@@ -42,7 +42,7 @@ function TooltipContent({
42
42
  data-slot="tooltip-content"
43
43
  sideOffset={sideOffset}
44
44
  className={cn(
45
- "bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
45
+ "bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-[1300] w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
46
46
  className
47
47
  )}
48
48
  {...props}
@@ -250,6 +250,47 @@ test('buildChatModel disables parallel_tool_calls for Ollama local to avoid dupl
250
250
  assert.equal(llm.clientConfig?.baseURL, 'http://localhost:11434/v1')
251
251
  })
252
252
 
253
+ test('buildChatModel passes JSON format mode only to local Ollama structured calls', () => {
254
+ const local = buildChatModel({
255
+ provider: 'ollama',
256
+ model: 'gemma4:e4b',
257
+ ollamaMode: 'local',
258
+ apiKey: null,
259
+ responseFormat: 'json_object',
260
+ }) as ChatOpenAI & { modelKwargs?: Record<string, unknown> }
261
+
262
+ assert.equal(local.modelKwargs?.parallel_tool_calls, false)
263
+ assert.equal(local.modelKwargs?.format, 'json')
264
+
265
+ saveCredentials({
266
+ 'cred-ollama-cloud-json': {
267
+ id: 'cred-ollama-cloud-json',
268
+ provider: 'ollama',
269
+ name: 'Ollama Cloud',
270
+ encryptedKey: encryptKey('ollama-cloud-key'),
271
+ createdAt: Date.now(),
272
+ },
273
+ } as Record<string, {
274
+ id: string
275
+ provider: string
276
+ name: string
277
+ encryptedKey: string
278
+ createdAt: number
279
+ }>)
280
+
281
+ const cloud = buildChatModel({
282
+ provider: 'ollama',
283
+ model: 'glm-5:cloud',
284
+ ollamaMode: 'cloud',
285
+ apiKey: null,
286
+ credentialId: 'cred-ollama-cloud-json',
287
+ responseFormat: 'json_object',
288
+ }) as ChatOpenAI & { modelKwargs?: Record<string, unknown> }
289
+
290
+ assert.equal(cloud.modelKwargs?.parallel_tool_calls, false)
291
+ assert.equal(cloud.modelKwargs?.format, undefined)
292
+ })
293
+
253
294
  test('buildChatModel uses a reasoning_content-preserving bridge for DeepSeek', () => {
254
295
  const llm = buildChatModel({
255
296
  provider: 'deepseek',
@@ -18,6 +18,7 @@ const OLLAMA_CLOUD_URL = 'https://ollama.com/v1'
18
18
  const OLLAMA_LOCAL_URL = 'http://localhost:11434/v1'
19
19
  export const OPENAI_COMPAT_MODEL_TIMEOUT_MS = 180_000
20
20
  export const OPENAI_COMPAT_MODEL_MAX_RETRIES = 2
21
+ export type GenerationResponseFormat = 'json_object'
21
22
 
22
23
  export interface GenerationModelPreference {
23
24
  provider?: string | null
@@ -27,6 +28,7 @@ export interface GenerationModelPreference {
27
28
  apiEndpoint?: string | null
28
29
  gatewayProfileId?: string | null
29
30
  thinkingLevel?: 'minimal' | 'low' | 'medium' | 'high' | null
31
+ responseFormat?: GenerationResponseFormat | null
30
32
  }
31
33
 
32
34
  interface ResolvedGenerationModelConfig {
@@ -36,6 +38,7 @@ interface ResolvedGenerationModelConfig {
36
38
  apiKey: string | null
37
39
  apiEndpoint: string | null
38
40
  thinkingLevel?: 'minimal' | 'low' | 'medium' | 'high'
41
+ responseFormat?: GenerationResponseFormat
39
42
  }
40
43
 
41
44
  type OpenAiReasoningEffort = 'low' | 'medium' | 'high'
@@ -43,6 +46,7 @@ type ChatOpenAiConfig = ConstructorParameters<typeof ChatOpenAI>[0] & {
43
46
  modelKwargs?: {
44
47
  reasoning_effort?: OpenAiReasoningEffort
45
48
  parallel_tool_calls?: boolean
49
+ format?: 'json'
46
50
  }
47
51
  configuration?: {
48
52
  baseURL?: string
@@ -68,8 +72,9 @@ export function buildChatModel(opts: {
68
72
  credentialId?: string | null
69
73
  apiEndpoint?: string | null
70
74
  thinkingLevel?: 'minimal' | 'low' | 'medium' | 'high'
75
+ responseFormat?: GenerationResponseFormat
71
76
  }) {
72
- const { provider, model, ollamaMode, apiKey, credentialId, apiEndpoint, thinkingLevel } = opts
77
+ const { provider, model, ollamaMode, apiKey, credentialId, apiEndpoint, thinkingLevel, responseFormat } = opts
73
78
  const resolvedCredentialId = resolveProviderCredentialId({ provider, ollamaMode: ollamaMode ?? null, credentialId })
74
79
  const resolvedApiKey = apiKey ?? resolveApiKeyFromCredential(resolvedCredentialId)
75
80
  const providers = getProviderList()
@@ -118,7 +123,10 @@ export function buildChatModel(opts: {
118
123
  timeout: OPENAI_COMPAT_MODEL_TIMEOUT_MS,
119
124
  maxRetries: OPENAI_COMPAT_MODEL_MAX_RETRIES,
120
125
  configuration: { baseURL },
121
- modelKwargs: { parallel_tool_calls: false },
126
+ modelKwargs: {
127
+ parallel_tool_calls: false,
128
+ ...(responseFormat === 'json_object' && !runtime.useCloud ? { format: 'json' as const } : {}),
129
+ },
122
130
  })
123
131
  }
124
132
 
@@ -222,6 +230,7 @@ function resolvePreferredGenerationConfig(
222
230
  apiKey,
223
231
  apiEndpoint,
224
232
  thinkingLevel: candidate.thinkingLevel || undefined,
233
+ responseFormat: candidate.responseFormat || undefined,
225
234
  }
226
235
  }
227
236
  return null
@@ -232,6 +241,7 @@ export function resolveGenerationModelConfig(options?: {
232
241
  sessionId?: string | null
233
242
  agentId?: string | null
234
243
  excludeProviders?: string[]
244
+ responseFormat?: GenerationResponseFormat
235
245
  }): ResolvedGenerationModelConfig {
236
246
  const providers = getProviderList()
237
247
  const excludeProviders = new Set((options?.excludeProviders || []).map((value) => normalizePreferenceValue(value)).filter(Boolean))
@@ -252,7 +262,9 @@ export function resolveGenerationModelConfig(options?: {
252
262
  ...getAgentGenerationPreferences(sessionAgent),
253
263
  ...getAgentGenerationPreferences(directAgent),
254
264
  ], excludeProviders)
255
- if (resolved) return resolved
265
+ if (resolved) return options?.responseFormat
266
+ ? { ...resolved, responseFormat: options.responseFormat }
267
+ : resolved
256
268
 
257
269
  const sessionLabel = options?.sessionId ? `session "${options.sessionId}"` : null
258
270
  const agentLabel = options?.agentId ? `agent "${options.agentId}"` : null
@@ -271,6 +283,7 @@ export async function buildLLM(options?: {
271
283
  sessionId?: string | null
272
284
  agentId?: string | null
273
285
  excludeProviders?: string[]
286
+ responseFormat?: GenerationResponseFormat
274
287
  }) {
275
288
  const resolved = resolveGenerationModelConfig(options)
276
289
  return {
@@ -0,0 +1,42 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+ import { parseTier2DreamResponseText } from './dream-service'
4
+
5
+ describe('parseTier2DreamResponseText', () => {
6
+ it('parses a plain structured dream response', () => {
7
+ const parsed = parseTier2DreamResponseText(JSON.stringify({
8
+ consolidations: [{
9
+ sourceIds: ['mem-1', 'mem-2'],
10
+ title: 'Shared pattern',
11
+ content: 'Both memories describe the same workflow.',
12
+ }],
13
+ reflections: [{ title: 'Focus', content: 'The agent prefers short release loops.' }],
14
+ flagged: [{ memoryId: 'mem-3', reason: 'Contradicts the current release process.' }],
15
+ }))
16
+
17
+ assert.deepEqual(parsed?.consolidations?.[0]?.sourceIds, ['mem-1', 'mem-2'])
18
+ assert.equal(parsed?.reflections?.[0]?.title, 'Focus')
19
+ assert.equal(parsed?.flagged?.[0]?.memoryId, 'mem-3')
20
+ })
21
+
22
+ it('extracts fenced JSON with nested braces inside strings', () => {
23
+ const parsed = parseTier2DreamResponseText([
24
+ '```json',
25
+ '{',
26
+ ' "consolidations": [{',
27
+ ' "sourceIds": ["mem-1"],',
28
+ ' "title": "Payload shape",',
29
+ ' "content": "The JSON example was {\\"ok\\":true} and should stay intact."',
30
+ ' }]',
31
+ '}',
32
+ '```',
33
+ ].join('\n'))
34
+
35
+ assert.equal(parsed?.consolidations?.[0]?.content, 'The JSON example was {"ok":true} and should stay intact.')
36
+ })
37
+
38
+ it('rejects malformed or schema-incompatible responses', () => {
39
+ assert.equal(parseTier2DreamResponseText('no json here'), null)
40
+ assert.equal(parseTier2DreamResponseText('{"consolidations":[{"sourceIds":[123],"title":"Bad","content":"Bad"}]}'), null)
41
+ })
42
+ })
@@ -1,9 +1,10 @@
1
1
  import crypto from 'crypto'
2
+ import { z } from 'zod'
2
3
  import type { DreamCycle, DreamCycleResult, DreamConfig, DreamTrigger, Agent } from '@/types'
3
4
  import { DEFAULT_DREAM_CONFIG } from '@/types/dream'
4
5
  import { getMemoryDb } from '@/lib/server/memory/memory-db'
5
6
  import { saveDreamCycle } from '@/lib/server/memory/dream-cycles'
6
- import { errorMessage, safeJsonParse } from '@/lib/shared-utils'
7
+ import { errorMessage } from '@/lib/shared-utils'
7
8
  import { log } from '@/lib/server/logger'
8
9
 
9
10
  const TAG = 'dream-service'
@@ -102,6 +103,70 @@ interface Tier2Response {
102
103
  flagged?: Tier2Flagged[]
103
104
  }
104
105
 
106
+ const Tier2ResponseSchema = z.object({
107
+ consolidations: z.array(z.object({
108
+ sourceIds: z.array(z.string()),
109
+ title: z.string(),
110
+ content: z.string(),
111
+ })).optional(),
112
+ reflections: z.array(z.object({
113
+ title: z.string(),
114
+ content: z.string(),
115
+ })).optional(),
116
+ flagged: z.array(z.object({
117
+ memoryId: z.string(),
118
+ reason: z.string(),
119
+ })).optional(),
120
+ }).passthrough()
121
+
122
+ function findBalancedJsonObjectEnd(text: string, start: number): number {
123
+ let depth = 0
124
+ let inString = false
125
+ let escaped = false
126
+
127
+ for (let index = start; index < text.length; index += 1) {
128
+ const char = text[index]
129
+ if (inString) {
130
+ if (escaped) escaped = false
131
+ else if (char === '\\') escaped = true
132
+ else if (char === '"') inString = false
133
+ continue
134
+ }
135
+ if (char === '"') {
136
+ inString = true
137
+ continue
138
+ }
139
+ if (char === '{') depth += 1
140
+ else if (char === '}') depth -= 1
141
+ if (depth === 0) return index + 1
142
+ }
143
+ return -1
144
+ }
145
+
146
+ function extractFirstBalancedJsonObject(text: string): string | null {
147
+ const source = String(text || '')
148
+ for (let index = 0; index < source.length; index += 1) {
149
+ if (source[index] !== '{') continue
150
+ const end = findBalancedJsonObjectEnd(source, index)
151
+ if (end === -1) return null
152
+ return source.slice(index, end)
153
+ }
154
+ return null
155
+ }
156
+
157
+ export function parseTier2DreamResponseText(text: string): Tier2Response | null {
158
+ const jsonText = extractFirstBalancedJsonObject(text)
159
+ if (!jsonText) return null
160
+ let raw: unknown
161
+ try {
162
+ raw = JSON.parse(jsonText)
163
+ } catch {
164
+ return null
165
+ }
166
+ const parsed = Tier2ResponseSchema.safeParse(raw)
167
+ return parsed.success ? parsed.data : null
168
+ }
169
+
105
170
  export async function runTier2Dream(
106
171
  agentId: string,
107
172
  config: DreamConfig,
@@ -149,7 +214,7 @@ ${memoryLines.join('\n')}`
149
214
 
150
215
  try {
151
216
  const { buildLLM } = await import('@/lib/server/build-llm')
152
- const { llm } = await buildLLM({ agentId })
217
+ const { llm } = await buildLLM({ agentId, responseFormat: 'json_object' })
153
218
  const { HumanMessage } = await import('@langchain/core/messages')
154
219
 
155
220
  const response = await llm.invoke([new HumanMessage(prompt)])
@@ -159,9 +224,10 @@ ${memoryLines.join('\n')}`
159
224
  ? response.content.map((b) => ('text' in b && typeof b.text === 'string' ? b.text : '')).join('')
160
225
  : ''
161
226
 
162
- // Extract JSON from response (handle markdown code blocks)
163
- const jsonMatch = text.match(/\{[\s\S]*\}/)
164
- const parsed = safeJsonParse<Tier2Response>(jsonMatch?.[0] ?? '', {})
227
+ const parsed = parseTier2DreamResponseText(text) ?? {}
228
+ if (!parsed.consolidations && !parsed.reflections && !parsed.flagged) {
229
+ errors.push('Tier 2 dream response was not valid structured JSON.')
230
+ }
165
231
 
166
232
  // Process consolidations
167
233
  if (Array.isArray(parsed.consolidations)) {