Merge pull request #8289 from deepseek-harness/xtr/content-to-text

refactor(llm): 统一内容块文本提取
This commit is contained in:
_Kerman authored and GitHub committed 2026-11-16 20:58:31 +08:00
commit cd0252b813
36 files changed
+154 -138

No files matched your search

+8 -8
View File
@@ -1127,7 +1127,7 @@ export interface StagehandModelConfig {
## `@deepseek-ai/dsh-experimental-claude-code-mods`
- `inject`: `workingDirectory` · `agents`
- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts)
- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts)
```ts config-catalog
/** Plugin config: the limits mod hooks run under. */
@@ -1727,7 +1727,7 @@ export interface Config {
- `inject`: `agentDefaultModel` · `agents` · `sessions`
- `refs`: [`ApprovalPolicy`](subsystems/approval.md)
- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts)
- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts)
```ts config-catalog
/** Plugin config: the task and run options resolved from this app's injected provider service. */
@@ -1775,7 +1775,7 @@ export interface HmrConfig extends ChokidarOptions {
## `@deepseek-ai/dsh-hooks-claude-code`
- `inject`: `shell` · `agents` · `workingDirectory`
- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts)
- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:54`](../packages/experimental/hooks-claude-code/src/index.ts)
```ts config-catalog
/** Plugin config: where the CC hook config lives + substitution roots. */
@@ -1814,7 +1814,7 @@ export interface Config {
## `@deepseek-ai/dsh-hooks-codex`
- `inject`: `shell` · `agents` · `workingDirectory`
- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts)
- `source`: [`packages/experimental/hooks-codex/src/index.ts:53`](../packages/experimental/hooks-codex/src/index.ts)
```ts config-catalog
/** Plugin config: where the Codex hooks.json lives + the model name for payloads. */
@@ -3446,7 +3446,7 @@ export enum SessionTelemetryMode {
## `@deepseek-ai/dsh-session-title`
- `inject`: `sessions` · `sessionProjections` · `agents`
- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts)
- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts)
```ts config-catalog
/** Required deterministic fallback and accepted-title limits. */
@@ -3468,7 +3468,7 @@ export interface Config {
- `inject`: `sessionTitle` · `llm` · `sessions`
- `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts)
- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts)
- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:30`](../packages/experimental/session-title-all-prompts-llm/src/index.ts)
```ts config-catalog
/** Required execution controls plus this provider's title-length targets; no defaults. */
@@ -3488,7 +3488,7 @@ export interface Config extends SessionTitleLlmConfig {
- `inject`: `sessionTitle` · `llm` · `sessions`
- `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts)
- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts)
- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:30`](../packages/session/session-title-first-prompt-llm/src/index.ts)
```ts config-catalog
/** Required execution controls plus this provider's title-length targets; no defaults. */
@@ -5024,7 +5024,7 @@ export interface Config {
- `inject`: `web`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts)
```ts config-catalog
/**
+8 -8
View File
@@ -1129,7 +1129,7 @@ export interface StagehandModelConfig {
## `@deepseek-ai/dsh-experimental-claude-code-mods`
- `inject`: `workingDirectory` · `agents`
- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts)
- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts)
```ts config-catalog
/** Plugin config: the limits mod hooks run under. */
@@ -1729,7 +1729,7 @@ export interface Config {
- `inject`: `agentDefaultModel` · `agents` · `sessions`
- `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md)
- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts)
- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts)
```ts config-catalog
/** Plugin config: the task and run options resolved from this app's injected provider service. */
@@ -1777,7 +1777,7 @@ export interface HmrConfig extends ChokidarOptions {
## `@deepseek-ai/dsh-hooks-claude-code`
- `inject`: `shell` · `agents` · `workingDirectory`
- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts)
- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:54`](../packages/experimental/hooks-claude-code/src/index.ts)
```ts config-catalog
/** Plugin config: where the CC hook config lives + substitution roots. */
@@ -1816,7 +1816,7 @@ export interface Config {
## `@deepseek-ai/dsh-hooks-codex`
- `inject`: `shell` · `agents` · `workingDirectory`
- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts)
- `source`: [`packages/experimental/hooks-codex/src/index.ts:53`](../packages/experimental/hooks-codex/src/index.ts)
```ts config-catalog
/** Plugin config: where the Codex hooks.json lives + the model name for payloads. */
@@ -3448,7 +3448,7 @@ export enum SessionTelemetryMode {
## `@deepseek-ai/dsh-session-title`
- `inject`: `sessions` · `sessionProjections` · `agents`
- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts)
- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts)
```ts config-catalog
/** Required deterministic fallback and accepted-title limits. */
@@ -3470,7 +3470,7 @@ export interface Config {
- `inject`: `sessionTitle` · `llm` · `sessions`
- `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts)
- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts)
- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:30`](../packages/experimental/session-title-all-prompts-llm/src/index.ts)
```ts config-catalog
/** Required execution controls plus this provider's title-length targets; no defaults. */
@@ -3490,7 +3490,7 @@ export interface Config extends SessionTitleLlmConfig {
- `inject`: `sessionTitle` · `llm` · `sessions`
- `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts)
- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts)
- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:30`](../packages/session/session-title-first-prompt-llm/src/index.ts)
```ts config-catalog
/** Required execution controls plus this provider's title-length targets; no defaults. */
@@ -5026,7 +5026,7 @@ export interface Config {
- `inject`: `web`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts)
```ts config-catalog
/**
+1 -1
View File
@@ -60,7 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - |
| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
+1 -1
View File
@@ -62,7 +62,7 @@
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - |
| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
+2 -2
View File
@@ -183,8 +183,8 @@
en: 20645a60e921f012
zh: 7141cafe3a0e71d7
/session-persistence-event-catalog/events/session/session-title-log-only:
en: 6c6a27578dff5828
zh: 9a5add2bc0df2d0a
en: 5775e52a72c0ce94
zh: fa211a35b4660c10
/session-persistence-event-catalog/events/session/session-title-llm-request-log-only:
en: 59b02baa2be32ca0
zh: 3637c99652ca89cf
+1 -1
View File
@@ -865,7 +865,7 @@ Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/
Types: [SessionTitleEventData](subsystems/session-title.md)
Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts)
Source: [`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts)
<a id="sessiontitle-llm-request--log-only"></a>
+1 -1
View File
@@ -867,7 +867,7 @@ export type SessionEvent<T extends SessionEventType = SessionEventType> = {
类型:[SessionTitleEventData](subsystems/session-title.zh.md)
来源:[`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts)
来源:[`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts)
<a id="sessiontitle-llm-request--log-only"></a>
+2 -4
View File
@@ -18,6 +18,7 @@ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-agent-default-model'
import { installModelSelection } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-fs'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { APPROVAL_POLICIES, setApprovalPolicy, type ApprovalPolicy } from '@deepseek-ai/dsh-user-approval'
import { assertNever } from '@deepseek-ai/dsh-util-values'
@@ -99,10 +100,7 @@ function summarize(session: Session, firstSeq: SessionLogOffset): RunOutcome {
}
if (!started) continue
if (event.type === 'assistant/message') {
const joined = event.data.message.content
.filter(block => block.type === 'text')
.map(block => block.text)
.join('')
const joined = extractTextContent(event.data.message.content)
if (joined !== '') text = joined
}
if (event.type === 'turn/end') reason = event.data.reason
@@ -1,3 +1,4 @@
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { Context } from '@deepseek-ai/cordis'
import type {
CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,
@@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver
if (match?.event.type === 'compaction/summary') {
const data = match.event.data
if (Array.isArray(data.summary)) {
const text = data.summary
.map(block => block.type === 'text' ? block.text : '')
.join('')
const text = extractTextContent(data.summary)
summary = text.trim() === '' ? null : text
}
shadowedItemCount = Array.isArray(data.shadowedSeqs)
@@ -1,4 +1,5 @@
/** Immutable system-only interpretation of the loaded Session surface. */
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface'
import type { SystemPromptNode } from './request-inspection.ts'
@@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve
time: event.time,
turn: event.data.turn,
step: event.data.step,
text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''),
text: extractTextContent(event.data.message.content),
update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true,
}
: undefined
@@ -1,3 +1,4 @@
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { Context } from '@deepseek-ai/cordis'
import { useEffect, useId, useMemo, useState } from 'react'
import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
@@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly<Partial<UserTextFacts>> = {
function textOf(content: InboxState['next-turn'][number]['content']): string | null {
if (!content.every(block => block.type === 'text')) return null
return content.map(block => block.text).join('')
return extractTextContent(content)
}
/** Queue operations injected by the session-scoped registration. */
@@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load
</span>
)}
<span className={css.preview}>{renderFactorySlot('conversation.user.text', {
text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''),
text: extractTextContent(row.content),
facts: QUEUE_TEXT_FACTS,
interactive: false, ellipsis: true,
})}</span>
@@ -1,6 +1,7 @@
// Office toolview links target the input, not the temporary output. Rows show the
// result's text blocks; rendered page images reach the model but are not displayed.
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import type { Context } from '@deepseek-ai/cordis'
import { toolFileInject } from '../file-menu.ts'
@@ -26,7 +27,7 @@ export function OfficeRow({
const row = toolRowModel(toolName, block, cwd, home)
// Image blocks flatten to JSON attachment references, so a settled result with only images shows no body.
const output = 'kind' in block
? block.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n') || null
? extractTextContent(block.content, { separator: '\n' }) || null
: row.output
const path = office.filePath
return (
@@ -1,5 +1,7 @@
/** Current-surface projection and byte-bounded rendering. */
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction'
import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query'
import { TextRetainer } from '@deepseek-ai/dsh-output-retention'
@@ -42,12 +44,12 @@ function projectSessionConversation(snapshot: SessionSurfaceSnapshot): Projected
case 'user/message': {
const checkpoint = isCompactCheckpointSource(event.data.source)
if (!checkpoint && event.data.source.kind !== 'user') break
const text = textContent(event.data.content)
const text = extractTextContent(event.data.content, { separator: '\n' })
if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 })
break
}
case 'assistant/message': {
const text = textContent(event.data.message.content)
const text = extractTextContent(event.data.message.content, { separator: '\n' })
if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 })
break
}
@@ -145,10 +147,6 @@ export function retainReferencedSession(
}
}
function textContent(content: readonly { type: string; text?: string }[]): string {
return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n')
}
function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } {
/* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */
if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 }
+2 -1
View File
@@ -10,6 +10,7 @@ import { isDeepStrictEqual } from 'node:util'
import type { PtcDispatchLog } from './runtime-types.ts'
import { symbols, type Context } from '@deepseek-ai/cordis'
import { brandString } from '@deepseek-ai/dsh-brand'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm'
@@ -621,7 +622,7 @@ export function createRunCodeTransport(
if (first !== undefined && images.length === 1) return programImage(first.attachment)
if (outcome.imageRemoved) {
throw new Error('Image output was removed by a tool output policy.\n'
+ outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n'))
+ extractTextContent(outcome.content, { separator: '\n' }))
}
if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image')
}
@@ -17,6 +17,7 @@ import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs'
import { brandString } from '@deepseek-ai/dsh-brand'
import { HarnessError } from '@deepseek-ai/dsh-error'
import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm'
import { scopeOf } from '@deepseek-ai/dsh-scope'
import type { WorkingDirectoryService } from '@deepseek-ai/dsh-working-directory'
@@ -116,17 +117,13 @@ function requireAgent(context: OpContext<AgentBinding>, op: string): Agent {
return agent
}
function textOf(content: readonly ContentBlock[]): string {
return content.filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text').map(block => block.text).join('')
}
/**
* Project one tool outcome onto Claude Code's `tool.call` result.
* @param result - the harness tool outcome.
* @returns its text as `result`, with `isError` on a failure.
*/
export function toolCallResultOf(result: ToolExecutionResult): ToolCallResult {
return result.isError ? { result: textOf(result.content), isError: true } : { result: textOf(result.content) }
return result.isError ? { result: extractTextContent(result.content), isError: true } : { result: extractTextContent(result.content) }
}
/** The model's raw JSON arguments as an object; an unparsable string is an empty input. */
@@ -146,7 +143,7 @@ function sessionMessages(messages: readonly Message[], aliases: ToolNameAliases)
const toolUses = message.content
.filter((block): block is Extract<ContentBlock, { type: 'tool-call' }> => block.type === 'tool-call')
.map(block => ({ tool_use_id: block.id, tool: aliases.toMod(block.name), input: argumentsOf(block.arguments) }))
out.push({ role: message.role, text: textOf(message.content), toolUses })
out.push({ role: message.role, text: extractTextContent(message.content), toolUses })
}
return out
}
@@ -15,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-working-directory'
import z from '@deepseek-ai/schemastery'
import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
@@ -78,10 +79,6 @@ function assertPositive(field: string, value: number): void {
if (!Number.isFinite(value) || value <= 0) throw new Error(`claude-code-mods: ${field} must be a positive number of milliseconds`)
}
function textOf(blocks: readonly ContentBlock[]): string {
return blocks.filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text').map(block => block.text).join('')
}
/** The human's own messages among a claim: the prompt a `prompt.submit` hook sees and may rewrite. */
function promptMessages(claimed: readonly UserMessage[]): UserMessage[] {
return claimed.filter(message => message.source.kind === 'user')
@@ -141,7 +138,7 @@ interface TurnRecord {
/** Fold one committed assistant message into the turn's answer and usage. */
function foldAssistantMessage(turnRecord: TurnRecord, data: { message: AssistantMessage; usage?: TokenUsage }): void {
turnRecord.answer = textOf(data.message.content)
turnRecord.answer = extractTextContent(data.message.content)
if (data.usage === undefined) return
const { model } = data.message.source
const usage = turnRecord.usage ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model }
@@ -349,7 +346,7 @@ export class ClaudeCodeMods extends TypertRemoteService {
const first = !started.has(turn)
started.add(turn)
const prompt = promptMessages(messages)
const text = textOf(prompt.flatMap(message => message.content))
const text = extractTextContent(prompt.flatMap(message => message.content))
let submitted: PromptSubmitResult = { text }
// A batch of injected context alone is not a prompt: Claude Code raises prompt.submit for typed prompts.
if (prompt.length > 0) {
@@ -1,5 +1,6 @@
/** Event folding and per-step metric derivation for the Statistics table. */
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { SessionEventLike } from '@deepseek-ai/dsh-api-session-controller/client'
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { AssistantMessage, ContentBlock, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm'
@@ -267,10 +268,7 @@ const OPAQUE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9
export function triggerSenderOf(message: UserMessage): string | null {
const kind: string = message.source.kind
if (kind !== 'agent-message' && kind !== 'team-message') return null
let text = ''
for (const block of message.content) {
if (block.type === 'text') text += block.text
}
const text = extractTextContent(message.content)
const team = TEAM_MESSAGE_PREFIX.exec(text)
/* v8 ignore next -- a matched capture group is always present. */
if (team !== null) return team[1]?.trim() ?? null
@@ -291,11 +289,7 @@ function answerOf(message: AssistantMessage): {
body: string
truncated: boolean
} | null {
const parts: string[] = []
for (const block of message.content) {
if (block.type === 'text') parts.push(block.text)
}
const text = parts.join('\n').trim()
const text = extractTextContent(message.content, { separator: '\n' }).trim()
if (text === '') return null
return {
preview: text.length > ANSWER_LIMIT ? text.slice(0, ANSWER_LIMIT) : text,
@@ -4,7 +4,7 @@
*/
import { z } from 'zod'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { pluginRecordOf, SessionSeq } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session'
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
@@ -104,7 +104,7 @@ export function forgeChangeRequestsProjection(rules: CommandRules): ForgeChangeR
if (pending === undefined) return state
const settled = { ...state, pending: state.pending.filter(entry => entry !== pending) }
if (result.message.isError === true) return settled
return settle(settled, pending, textOf(result.message.content), seq)
return settle(settled, pending, extractTextContent(result.message.content, { separator: '\n' }), seq)
}
const applyDispatch = (
@@ -114,7 +114,7 @@ export function forgeChangeRequestsProjection(rules: CommandRules): ForgeChangeR
const command = commandIn(dispatch.arguments)
const evidence = command === undefined || !rules.hint.test(command) ? undefined : rules.evidence(command)
if (evidence === undefined) return state
return settle(state, evidence, textOf(dispatch.content), seq)
return settle(state, evidence, extractTextContent(dispatch.content, { separator: '\n' }), seq)
}
/** Bind the URLs and record the pushes one successful shell result carries; returns the input state when nothing changes. */
@@ -136,11 +136,6 @@ export function forgeChangeRequestsProjection(rules: CommandRules): ForgeChangeR
}
}
/** Text blocks of a rendered shell result, joined by newlines. */
function textOf(content: readonly ContentBlock[]): string {
return content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
}
function applyRecord(state: ForgeChangeRequestsState, event: SessionEvent): ForgeChangeRequestsState {
const record = pluginRecordOf(event)
if (record?.type !== BINDING_RECORD) return state
@@ -1,6 +1,7 @@
/** Resolve unqualified CLI references in the shell execution world and persist only confirmed URLs. */
import type { Context } from '@deepseek-ai/cordis'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { Session } from '@deepseek-ai/dsh-session'
import type { ToolExecution, ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools'
import type {} from '@deepseek-ai/dsh-shell'
@@ -89,7 +90,7 @@ export function observeReferences(
const argumentsResult = shellArguments.safeParse(exec.arguments)
const shell = completedShell.safeParse(result.value)
if (!argumentsResult.success || !shell.success) return []
const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
const printed = extractTextContent(result.content, { separator: '\n' })
const current = rules()
const { command } = argumentsResult.data
const evidence = current.evidence(command)
@@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
declare module '@deepseek-ai/dsh-llm' {
@@ -327,11 +328,6 @@ function lastTurn(ctx: Context, agent: Agent | undefined): number {
return ctx.agents.turnBoundaryOf(agent.session).lastTurn
}
/** Flatten content blocks to the text a hook payload carries (the common case). */
function blocksToText(content: ContentBlock[]): string {
return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
}
function base(agent: Agent | undefined, event: string): Record<string, unknown> {
return {
session_id: agent?.session.header.id ?? '',
@@ -346,13 +342,13 @@ function sessionStartPayload(agent: Agent, source: string): Record<string, unkno
return { ...base(agent, 'SessionStart'), source }
}
function promptPayload(agent: Agent, content: ContentBlock[]): Record<string, unknown> {
return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) }
return { ...base(agent, 'UserPromptSubmit'), prompt: extractTextContent(content) }
}
function preToolPayload(exec: ToolExecution): Record<string, unknown> {
return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId }
}
function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record<string, unknown> {
return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) }
}
function stopPayload(agent: Agent): Record<string, unknown> {
return { ...base(agent, 'Stop'), stop_hook_active: false }
@@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
declare module '@deepseek-ai/dsh-llm' {
@@ -206,7 +207,7 @@ export function apply(ctx: Context, config: Config): void {
const payload = {
...base(agent, 'UserPromptSubmit', model),
turn_id: String(turn),
prompt: blocksToText(messages.flatMap(message => message.content)),
prompt: extractTextContent(messages.flatMap(message => message.content)),
}
const merged = await runPoint('UserPromptSubmit', '', payload, {
agent, turn, plainStdoutAsContext: true, signal,
@@ -283,17 +284,12 @@ export function apply(ctx: Context, config: Config): void {
// --- Codex DIALECT payloads: snake_case, model on every event, turn_id on
// turn-scoped events. ---
// These small payload helpers intentionally remain next to the dialect shape;
// sharing them would pull bridge-only agent/LLM dependencies into hook-protocol.
// Shared hook-protocol code has no Agent dependency, so turn lookup stays in the bridge.
/* jscpd:ignore-start */
function lastTurn(ctx: Context, agent: Agent | undefined): number {
if (!agent) return 0
return ctx.agents.turnBoundaryOf(agent.session).lastTurn
}
function blocksToText(content: ContentBlock[]): string {
return content.filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text').map(b => b.text).join('')
}
/* jscpd:ignore-end */
/** Base fields on every Codex payload (no turn_id). */
@@ -332,5 +328,5 @@ function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Recor
}
function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record<string, unknown> {
return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) }
return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) }
}
@@ -3,7 +3,8 @@
/* jscpd:ignore-start -- both shipped providers import the same shared packages. */
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types'
@@ -137,10 +138,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string {
if (response.blocks.some(block => block.type === 'tool-call')) {
throw new Error('session-title-llm: title output must contain text only')
}
const text = response.blocks
.filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text')
.map(block => block.text)
.join(' ')
const text = extractTextContent(response.blocks, { separator: ' ' })
const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER)
if (title.length === 0) throw new Error('session-title-llm: title model produced no text')
return title
+3 -3
View File
@@ -1,5 +1,6 @@
/** Map system snapshots, tool changes, and conversation turns to Messages using the configured route capability. */
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { LlmError, requestImageHandleText } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage } from '@deepseek-ai/dsh-llm'
import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment'
@@ -104,9 +105,8 @@ export function serialize(
return unsupported('tool-change blocks outside developer messages')
}
if (message.role === 'system') {
const texts = message.content.filter(block => block.type === 'text')
if (texts.length !== message.content.length) return unsupported('non-text system message')
const text = texts.map(block => block.text).join('')
if (message.content.some(block => block.type !== 'text')) return unsupported('non-text system message')
const text = extractTextContent(message.content)
if (inHistory && messages.length > 0) {
if (text.length === 0) return unsupported('empty in-history system update')
systemUpdates.push({ role: 'system', content: [{ type: 'text', text }] })
+6 -14
View File
@@ -5,6 +5,7 @@
*/
import { brandString } from '@deepseek-ai/dsh-brand'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage, ToolCallId } from '@deepseek-ai/dsh-llm'
import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types'
@@ -20,15 +21,6 @@ import type { PrefixDigests } from './prefix-binding.ts'
import { requestImageDimensions } from '@deepseek-ai/dsh-attachment'
import { DEFAULT_REQUEST_IMAGE_MAX_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET } from './config.ts'
/** Join the text blocks of a harness message. */
function flattenText(message: RequestMessage): string {
return message.content
.filter(block => block.type === 'text')
.map(block => block.text)
.join('')
}
/** Recover the pi-ai toolResult message for one harness tool-role message. */
function toolResultOf(
message: Extract<Message, { role: 'tool' }>,
@@ -94,7 +86,7 @@ function userContent(
break
}
}
if (content.every(block => block.type === 'text')) return content.map(block => block.text).join('')
if (content.every(block => block.type === 'text')) return extractTextContent(content)
return content
}
@@ -151,7 +143,7 @@ function splitSystemPrompt(options: GenerateOptions): SystemPromptSplit {
let end = 0
for (const message of options.messages) {
if (message.role !== 'system') break
text.push(flattenText(message))
text.push(extractTextContent(message.content))
end++
}
const systemPrompt = text.filter(Boolean).join('\n\n')
@@ -230,7 +222,7 @@ function appendSharedHistory(
return true
}
if (message.role === 'system') {
const content = flattenText(message)
const content = extractTextContent(message.content)
if (content.length > 0) {
if (supportsMidConvoSystemMessages) {
messages.push({ role: 'system', content, timestamp: 0 })
@@ -264,10 +256,10 @@ function textOnlyContext(
}
if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue
if (message.role === 'tool') {
messages.push(toolResultOf(message, toolNames, flattenText(message)))
messages.push(toolResultOf(message, toolNames, extractTextContent(message.content)))
continue
}
messages.push({ role: 'user', content: flattenText(message), timestamp: 0 })
messages.push({ role: 'user', content: extractTextContent(message.content), timestamp: 0 })
}
return piContext(split.systemPrompt, options, messages)
}
+4 -4
View File
@@ -24,8 +24,8 @@
en: cf221d60fb42a278
zh: 0ea17503495d386b
/deepseek-ai-dsh-llm/use-this-package/what-you-can-do:
en: dc61eb86585f6e0d
zh: 9c0d6b240dfd2cda
en: cb9f0c6ee3203ab3
zh: 8513340a40192513
/deepseek-ai-dsh-llm/use-this-package/failures-and-recovery:
en: 47f4dab3c377a4cd
zh: 49ac1c366de19136
@@ -36,8 +36,8 @@
en: 12d0444c18a397c7
zh: 9d4a5468b4bb7fcd
/deepseek-ai-dsh-llm/understand-the-implementation/source-map:
en: ae1618577f4e8364
zh: a6e8ab1563c08dfb
en: 8ec1ca8903e09bc0
zh: 77c7bc3413cbab1c
/deepseek-ai-dsh-llm/understand-the-implementation/main-flow:
en: c95d4947745e39bb
zh: ec37b969f27629e2
+2 -1
View File
@@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall =>
### What you can do
- **Extract content text** — `extractTextContent(content, options?)` from `@deepseek-ai/dsh-llm/message` joins only `text` blocks in order, preserving whitespace and empty text blocks while omitting all other block types without placeholders. The optional `options.separator` defaults to `''`. It accepts read-only content and returns `''` when no text blocks exist.
- **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`.
- **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`.
- **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable. An entry can also carry `defaultBaseURL`, the endpoint the adapter uses when the profile sets none, and `nativeAuth`, the environment variables and OAuth sign-in that the adapter's authentication reads when the profile names no credential reference; `baseURLEnv` lists environment variables used to configure the endpoint. Configuration UIs read these fields from the directory without calling the adapter.
@@ -116,7 +117,7 @@ The service is built on one separation: **the logical contract is provider-neutr
|---|---|
| [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary |
| [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary |
| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests |
| [`src/message.ts`](src/message.ts) | Content text extraction and immutable message constructors shared by delivery, history, and requests |
| [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly |
| [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers |
| [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing |
+2 -1
View File
@@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall =>
### 你可以做什么
- **提取内容文本**——从 `@deepseek-ai/dsh-llm/message` 导入的 `extractTextContent(content, options?)` 按顺序仅拼接 `text` 块,保留空白与空文本块,忽略所有其他块类型且不生成占位符。可选的 `options.separator` 默认为 `''`。它接受只读内容,没有文本块时返回 `''`。
- **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。
- **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。
- **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。条目还可携带 `defaultBaseURL`,即配置未设置端点时适配器使用的端点;以及 `nativeAuth`,即配置未指定凭据引用时适配器认证读取的环境变量与 OAuth 登录;`baseURLEnv` 列出配置端点所用的环境变量。配置界面直接从目录读取这些字段,无需调用适配器。
@@ -116,7 +117,7 @@ const configure = (maxTokens: number): ConfigureCall =>
|---|---|
| [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 |
| [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 |
| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 |
| [`src/message.ts`](src/message.ts) | 内容文本提取与投递、历史、请求共享的不可变消息构造函数 |
| [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 |
| [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 |
| [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 |
+5 -1
View File
@@ -49,7 +49,11 @@ export * from './api-key.ts'
export type * from './types.ts'
export * from './content.ts'
export * from './assistant-stream.ts'
export * from './message.ts'
export type * from './message.ts'
export {
CONTEXT_SUMMARY_MAX_CHARS, boundContextSummary, createAssistantMessage, createDeveloperMessage, createMessage,
createSystemMessage, createToolResultMessage, createUserMessage, freezeMessage,
} from './message.ts'
export * from './retry-policy.ts'
export { BlockAssembler } from './assembler.ts'
export { callConfigEquals, isAgentLoopRequest, markAgentLoopRequest } from './call-config.ts'
+14 -1
View File
@@ -1,4 +1,4 @@
/** Message value types, identity, and immutable construction helpers. */
/** Message value types, content text extraction, identity, and immutable construction helpers. */
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -304,3 +304,16 @@ export function createToolResultMessage(input: ToolResultMessageInput): ToolResu
isError: input.isError,
})
}
/**
* Extract and join only text blocks in content order, preserving their whitespace.
* Non-text blocks contribute neither text nor separators; content is not modified.
* Import from `@deepseek-ai/dsh-llm/message` in Host and browser code.
* @param content - source blocks to read in their existing order.
* @param options - optional text extraction settings.
* @param options.separator - text inserted between text blocks; defaults to an empty string.
* @returns joined text, or an empty string when no text blocks are present.
*/
export function extractTextContent(content: readonly ContentBlock[], options?: { separator?: string }): string {
return content.filter(block => block.type === 'text').map(block => block.text).join(options?.separator ?? '')
}
+41
View File
@@ -1,5 +1,6 @@
import { describe, expect, expectTypeOf, it } from 'vitest'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { AttachmentId } from '@deepseek-ai/dsh-attachment'
import {
type ToolCallId,
boundContextSummary,
@@ -12,6 +13,46 @@ import {
freezeMessage,
type MessageId,
} from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
describe('extractTextContent', () => {
it('preserves whitespace and empty text blocks while omitting non-text blocks', () => {
const message = createUserMessage({
source: { kind: 'test' },
content: [
{ type: 'text', text: ' \talpha\n' },
{ type: 'reasoning', text: 'private reasoning' },
{ type: 'image', attachment: {
attachmentId: brandString<AttachmentId>(`sha256:${'a'.repeat(64)}`),
mediaType: 'image/png', bytes: 1, width: 1, height: 1,
} },
{ type: 'tool-call', id: brandString<ToolCallId>('call'), name: 'tool', arguments: '{}' },
{ type: 'text', text: '' },
{ type: 'tool-removal', toolName: 'removed' },
{ type: 'text', text: 'β \r\n' },
],
})
expect(extractTextContent(message.content)).toBe(' \talpha\nβ \r\n')
expect(extractTextContent(message.content, undefined)).toBe(' \talpha\nβ \r\n')
expect(extractTextContent(message.content, {})).toBe(' \talpha\nβ \r\n')
expect(extractTextContent(message.content, { separator: '' })).toBe(' \talpha\nβ \r\n')
expect(extractTextContent(message.content, { separator: '\n' })).toBe(' \talpha\n\n\nβ \r\n')
expect(extractTextContent(message.content, { separator: ' ' })).toBe(' \talpha\n β \r\n')
expect(extractTextContent(message.content, { separator: '::' })).toBe(' \talpha\n::::β \r\n')
expect(Object.isFrozen(message.content)).toBe(true)
expect(message.content[0]).toEqual({ type: 'text', text: ' \talpha\n' })
})
it('returns empty text when there are no text blocks and keeps separators between empty text blocks', () => {
expect(extractTextContent([])).toBe('')
expect(extractTextContent([{ type: 'reasoning', text: 'not plain text' }], { separator: '\n' })).toBe('')
expect(extractTextContent([
{ type: 'text', text: '' },
{ type: 'reasoning', text: 'ignored' },
{ type: 'text', text: '' },
], { separator: '\n' })).toBe('\n')
})
})
describe('message construction', () => {
it('detaches and freezes developer tool names without copying their definitions', () => {
+3 -1
View File
@@ -1,5 +1,7 @@
/** Observe command-admitted activity through quiescence and preserve a goal's first terminal outcome. */
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { GoalView } from '@deepseek-ai/dsh-goal'
@@ -63,7 +65,7 @@ export class QueryActivity {
}
if (this.input || this.goalId !== undefined) {
if (event.type === 'assistant/message') {
this.response = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
this.response = extractTextContent(event.data.message.content)
}
if (event.type === 'turn/end') this.turnReason = event.data.reason.kind
}
@@ -3,7 +3,8 @@
/* jscpd:ignore-start -- both shipped providers import the same shared packages. */
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types'
@@ -128,10 +129,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string {
if (response.blocks.some(block => block.type === 'tool-call')) {
throw new Error('session-title-llm: title output must contain text only')
}
const text = response.blocks
.filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text')
.map(block => block.text)
.join(' ')
const text = extractTextContent(response.blocks, { separator: ' ' })
const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER)
if (title.length === 0) throw new Error('session-title-llm: title model produced no text')
return title
+2 -4
View File
@@ -8,6 +8,7 @@ import z from '@deepseek-ai/schemastery'
import { z as zod } from 'zod'
import type { ZodType } from 'zod'
import type { Branded } from '@deepseek-ai/dsh-brand'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import { isAgentLoopRequest } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values'
@@ -137,10 +138,7 @@ export interface SessionTitleProvider {
function sessionTitleUserMessageOf(event: SessionEvent): SessionTitleUserMessage | undefined {
if (event.type !== 'user/message' || event.data.source.kind !== 'user') return undefined
const content = event.data.content
const text = content
.filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text')
.map(block => block.text)
.join('\n')
const text = extractTextContent(content, { separator: '\n' })
if (normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER).length === 0) return undefined
return { seq: event.seq, text }
}
+3 -2
View File
@@ -21,7 +21,8 @@ import z from '@deepseek-ai/schemastery'
import type {} from '@deepseek-ai/dsh-agent'
import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
import type {} from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import {
deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey,
} from '@deepseek-ai/dsh-llm-deepseek'
@@ -156,7 +157,7 @@ const CAPABILITY = {
function latestUserQuestion(session: Session | undefined): string | undefined {
const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user')
if (prompt === undefined) return undefined
return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
return extractTextContent(prompt.content, { separator: '\n' })
}
/**
@@ -1,4 +1,4 @@
/** Generated by scripts/gen-workflow-guest.ts. Do not edit directly. */
/** Self-contained ESM guest transported into the mounted PTC runtime. */
export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");Line truncated
export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");Line truncated
+2 -10
View File
@@ -7,7 +7,7 @@
import * as vm from 'node:vm'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools'
import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
@@ -34,14 +34,6 @@ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider',
/** Deferred Claude Code options we name explicitly in the rejection message. */
const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType'])
/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */
function outputText(blocks: ContentBlock[]): string {
return blocks
.filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')
.map(block => block.text)
.join('')
}
/** A short display label derived from the prompt when the script passes none. */
function defaultLabel(prompt: string): string {
const newline = prompt.indexOf('\n')
@@ -222,7 +214,7 @@ export class WorkflowExecution {
return result.structured
}
this.observer.agentEnd({ ...info, outcome: 'completed' })
return outputText(result.output)
return extractTextContent(result.output)
}
this.observer.agentEnd({ ...info, outcome: 'failed' })
return null